React Application Parent-Child Data Binding

Naveed Ahmed, Alizai
2 min readJan 14, 2021

--

Since the introduction of react hooks back in February 2019, Reactjs have gained more popularity. React hooks have not only made the development efficient but also flatten the learning curve even more. Because now react is totally based on functional components, it is easier to pass data from parent component to child components and vice versa. But sometimes it could be tricky to understand how to pass data from child-to-parent component. In this article we will see how we can pass the data both ways in the easiest way possible!

Before we start, have a look at react documentation to setup your project using create-react-app. Once your project is ready and running, you should see the following screen:

Parent-to-Child: We will add two react components called parent.js and child.js to our project src directory. To pass the data from parent to child component, import child component in parent component. We will add a new property in the "Child" tag which we have imported in parent component and then in the child component we will get the data with the same property name from the props object. In our example we will get an input and bind it to a custom react hook called "parentInput" and pass it to the child component as a property with name "toChild". Now when we write in the input control on the parent component, it will be reflected in the child component.

Child-to-Parent: To pass the data from child to parent component, we apply the same principle but in (kind of) reverse order as it can be seen in the code snippet below. First we create a custom react hook called "childInput" in parent component and pass the "setChildInput" setter for the hook to child component with the property name "fromChild". Now in the child component we take an input and pass the value from input event target to the property "fromChild" which act as a setter for "childInput" in the parent. This way whenever we write in the input of child component, it will automatically reflect in the "childInput" in the parent component.

The final output of the application will look like below:

project code can be found here

--

--