Friday, November 29, 2024
Google search engine
HomeLanguagesHow to lift state two levels up in ReactJS ?

How to lift state two levels up in ReactJS ?

We want to lift the state two levels up such that when an event occurs at the lower level component then it should affect the state two levels up. For example, there are three components X, Y, Z. X is the parent of Component Y, Component Y is the parent of Component Z. 

When some event occurs in component Z then it should affect the state of component X that is two-level up from component Z. for this we have to pass a function as a prop from component X to component Y then component Y will pass this function to component X so that Component X can call that function and change the state of component X.

Example: 

  • State of X

    this.state={ stateA: "whatever"}
  • Function in X:

    setStateX(newValue){
       this.setState({stateA: newValue});
    }
  • Now pass it as a prop to Y

    <Y setStateX={this.setStateX} />
  • In Y:

    <Z setStateX={this.props.setStateX} />
  • In Z:

    this.props.setStateX("new value of stateX");

Call the function to set the state of X.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Example:

App.js




import React from 'react'
  
class X extends React.Component {
  
    state = {
        name:"Kapil"
    }
  
    setStateX = (newState) => {
        this.setState({name:newState})
    }
      
    render() {
        return (
        <div>
        <h4>Hi my name is { this.state.name } </h4>
        <Y setStateX={this.setStateX}/>
        </div>
        );
    }
      
}
class Y extends React.Component {
  
    render() {
        return(
            <div>
                <Z setStateX = {this.props.setStateX}/>
            </div>
        );
    }
}
class Z extends React.Component {
    render() {
        return(
            <div>
                <button onClick = { ()=> {
                    this.props.setStateX("Nikhil")
                }}>click to change state</button>
            </div>
        )
    }
}
export default X;


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments