Connecting siblings components

What if we want to pass data through components who are siblings? And not parent and children? Then the solution is to initialize and maintain state to a common parent component of both siblings.

Since they are siblings, they should share a parent component! Then they can both have access to the state of the parent component, passed as props.

Already confused? Let’s see an example!

 

Parent component's structure

Let’s imagine you have a form with a single input field, and a paragraph that takes the value from this field and displays it. We have seen this before but your structure now has to be the one above.

Both the form, and the paragraph will be in autonomous components, and what they do contain we will find out soon. But what is essential for us, in order to make these components to communicate, is to put them under the same 'roof'. Under a common parent component. Above you can see that these two components are siblings, and children of the <App /> component.

In the <App /> component we will create the state, then we will give the ability to the <FormInput /> component to change this state. The <ShowUserInfo /> only depicts the current state. Anytime the state changes from the <FormInput />, the <App /> re-renders and the new changes are depicted from the <ShowUserInfo />.

Let's see what these siblings components look like.