Technically it’s not possible to pass props up to a parent in the same way you pass props down to a child. However, this article is going to propose two methods you can use that may help you solve the problem that bought you to this article.
The first method is something you probably do all the time. The second method is more realistic and may change the way you think about React components.
Method #1 — Pass a function down to change the prop
In this method, you store the property in the parent component and pass down a function that allows the child to update the prop stored in the parent component.
In the above code, we create state with
count and a function called
setCount that updates
setCount is then passed down to the child component, allowing it to update count.
Method #2 — Return an object, not just a component
We have to remember, React.js components are just functions and functions can return anything, including JSX.
In a screen I built recently, I had a parent component, a component that rendered some filters, and two components that make network requests and rendered the data returned from those network requests.
The filters component was complex and I wanted to contain it in a separate component, but the two components responsible for rendering data relied on the result of the filters.
The solution to this problem was for the filters components to return an object, that returned two properties. The first property is the result of the filters and the second is the JSX to render the filters.