I’m havin a parent component, let’s say “1”, it has 2 child components, “2” and “3”, each one of this components has one child component, “4” for “2” and “5” for “3”. So the question is how to pass state from the child component “5” to last component “4” ? Probably should I use composables approach? Could you show me an example?
Certainly! In React, you can pass state from a child component to its parent and then from the parent to another child component. One way to achieve this is by using callback functions. Here’s an example using functional components and the useState hook:
useState
import React, { useState } from 'react'; // Component 4 const Component4 = ({ stateFromChild5 }) => { return ( <div> <p>State from Child 5: {stateFromChild5}</p> {/* Component 4 content */} </div> ); }; // Component 5 const Component5 = ({ updateStateInChild4 }) => { const [stateInChild5, setStateInChild5] = useState(''); const handleButtonClick = () => { // Some logic to update state in Component 5 const newStateInChild5 = 'New State from Child 5'; setStateInChild5(newStateInChild5); // Callback to update state in Component 4 updateStateInChild4(newStateInChild5); }; return ( <div> <p>State in Child 5: {stateInChild5}</p> <button onClick={handleButtonClick}>Update State</button> {/* Component 5 content */} </div> ); }; // Component 3 const Component3 = () => { const [stateInChild4, setStateInChild4] = useState(''); // Callback function to update state in Component 4 const updateStateInChild4 = (newState) => { setStateInChild4(newState); }; return ( <div> <Component5 updateStateInChild4={updateStateInChild4} /> <Component4 stateFromChild5={stateInChild4} /> {/* Component 3 content */} </div> ); }; // Component 2 const Component2 = () => { return ( <div> <Component4 /> {/* Component 2 content */} </div> ); }; // Component 1 const Component1 = () => { return ( <div> <Component2 /> <Component3 /> {/* Component 1 content */} </div> ); }; export default Component1;
In this example, Component5 has a state (stateInChild5) that is updated when a button is clicked. It also calls the updateStateInChild4 prop, which is a callback function passed from Component3 to update the state in Component4. This way, state is passed from Component5 to Component4 through the parent components Component3 and Component1.
Component5
stateInChild5
updateStateInChild4
Component3
Component4
Component1