Back to all posts
dev•2 min read

How to Pass Props from Child Component to Parent Component in React 🤝⚛️

Hey there, In this post I'm going to show you how to pass props from a child component to a parent component in React.

Hey there, In this post I'm going to show you how to pass props from a child component to a parent component in React. Let's get started!

Okay, in order to share data between components in react we can use props. Due to unidirectional data flow pattern in react we can pass prop from parent to child. But how to pass from child to parent?

Confused? 😵

Alright, here's how you can pass prop from child to parent

Let's say you have Parent.js and Child.js

Parent.js

const Parent = (props) => {
  return (
    <div>
      <h1>Welcome! {/* name prop from child */}</h1>
    </div>
  );
};

Child.js

const Child = (props) => {
  // name prop to parent
  const name = 'Mohan';
  return <div>I'm the Child Component</div>;
};

So, now I want to send name from child to the parent.

In order to achieve that you need to pass a callback as a prop to the child from parent so that it can take that callback and pass the value as a parameter to the function and now it will be available in the parent.

Parent.js

const Parent = (props: any) => {
  const [state, setState] = useState('');
  const getValFromChild = (childProp: any) => {
    setState(childProp);
  };
  return (
    <div>
      <h1>Welcome {state}!</h1>
      <Child childToParentCallback={getValFromChild} />
    </div>
  );
};

Child.js

const Child = (props) => {
  const name = 'Mohan';
  props.childToParentCallback(name);
  return <div>I'm the Child Component</div>;
};

Now you can use the value from the child directly or you can also set it to a state.

Simple, right? 😉

Let me know your thoughts on this. See you on the next post. Bye!

Enjoyed this tutorial?

Share it with fellow developers on X (Twitter).

Share on X
M

Mohan Kumar

Web Developer & Tech Enthusiast. Building modern frontends, exploring creative coding, and sharing notes on software craftsmanship.