How to modify parent component in React
How do you change a sibling or parent component from a child component in React?

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
The premise is this: my colleagues at Staizen had to insert and update an action button (also known as CTA or Call To Action button) at the a component adjacent to itself.

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.
With this new requirement of a CTA button, we can't use Redux, since Redux only accepts plain objects. We can't even give it a callback, let alone modify the component's JSX during runtime.
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)
- Redux only allow plain JavaScript objects, so we can't solve this via global state
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
A code example
codesandbox.io/s/react-modify-adjacent-component-demo-d6xvkCover Photo by SHVETS production from Pexels