Passing data between components is a big part of using react. In this article, we look at how to pass those components using props and callbacks. You are probably thinking to yourself what are these things, if you already know the answer to that question no reason to keep reading this article. If you don’t know what they are, they are used to pass data between components from a parent component to a child component(props) or a child to a parent (callback). Now you might ask yourself how would you pass from sibling components, we will cover that as well.
Passing from Parent to Child
For this, you will use Props, while having access to data in the parent component that the child component needs access to you can pass the data as a prop.
Passing from Child to Parent
For this, you will use Callbacks, which is a little more difficult and not as straightforward as using props. To use callbacks we can use these steps…
- Define the callback in the parent component which will take the data needed as a parameter.
- Pass that callback as a prop to the child.
- Call that callback using this.props.[name used for callback] in the child, and then you will pass the data as the argument.
Passing from Siblings
To pass from two sibling components you will combine using props and callbacks. To do this you will be using the parent component as an intermediary. You can use these steps…
- Pass the data from the child to the parent, as an argument into a callback from the parent.
- Use the incoming parameter and set it as a state on the parent component.
- Pass the state as a prop to the other child component which will be the sibling of the first component.
After using those steps the sibling component will be able to access the data as a prop.
Passing data can be a bit tricky, but with practice and these tools, you can learn to master it and become a react pro.