In React, the way data flows is a one-way path, meaning that often child components are nested within parent components. This is important as this affects the way data is passed in React, specifically from a child component to a parent component.
To know how to pass data, it is helpful to understand why developers would want to pass data. One reason for passing data is for the separation of concerns. When developing components, some of the child components may be related, and instead of making a component that encompasses everything it is wiser to separate components that work together but can also act independently of one another. For instance, think of legos.
Each lego piece is independent of another piece but they can be added to parts of other legos that match. While this analogy to components is quite broad, it still gets across the idea of smaller individual pieces adding up to a hole. The benefit of coding like this is that debugging can be easier if you which specific component is problematic.
Now to actually pass data from Parent to Child
In regards to passing from a parent component to a child, the steps are really simple, and involves… props! Props are objects that are immutable or its values cannot be changed. Props are declared in the parent component and can be passed down through the use of the keyword this. If you are familiar with pseudoclassical instantiation then this should make sense.
Here is an example of a parent passing down its prop to a child component.
The parent component passes the props and the child can access it with the keyword this.props.
From Child to Parent
Going from child to parent in React is more difficult but not impossible. The way we accomplish passing data up to a parent is through the use of callbacks. The parent should have a callback function that can access the data from the child. Next, the parent passes the callback as a prop to the child, and lastly, the child will call the parent’s callback function through the child’s props. An example of this would look like this…
Finally, we come to end. As a recap, passing data is vital as it allows each component to specifically handle a specific task and be able to work as a unit. The ways we do this are different from passing down using props and passing up relying on callbacks and props.