If you need to change a sibling or parent component in React from a child component, how would you do it? - React State Lifting
Inserting a Call To Action Button
As the architecture diagram above, we need the Page Content component to control and modify the CTA button within the Page Title component. This means we would modify the button label, callback function and maybe even replace the button entirely with another UI widget.
The problem is, our current application only requires a string for the Page Title component. Before this, there was no existing requirement for it to hold a button, let alone one that is controlled by its sibling component. So, naturally we were using Redux. Each individual Page Content will modify the string in the Page Title via redux actions. Its a simple and elegant solution - until we had to add a dynamic button.
These are the problems we have to solve:
- The CTA button can only be generated by the Page Content
- The CTA button is dynamic (we should not have a predefine set of components)
So, what is the solution?
State Lifting - Back to the Fundamentals of React
One of the core fundamental concepts of React is State Lifting. Its often described as a technique where we hand control of the child component to the parent. But it can be a lot more powerful than that. When we do State Lifting, we are pulling back on the abstraction that separates child and parental components.
The solution: To implement this, we need to declare a state in the parent component. This state will hold a React Component. We will use this state to communicate between the 2 children. The Page Content will set the state to whatever component it desires, and the Page Title will listen to the state and apply the state directly in its JSX.
TL;DR we will
- declare a state in the parent to store a React component
- prop passing that state to the children so they can use it in their JSX as needed
- prop pass the setState function to any children who needs to insert or update a different component, essentially changing the behvaior of its parent or sibling