Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to update parent state in ReactJS ?

How to update parent state in ReactJS ?

We can pass a function setting the state from the parent to the child component as a prop.

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.

Project Structure

Filename: App.js

Javascript




import React, { Component } from "react";
class App extends Component {
  
  state = {
    text: 'click me'
  }
  
  // Function to update state
  handleUpdate = (newtext) => {
    this.setState({ text: newtext })
  }
  
  render() {
    return (
      <div>
        <Child
          text={this.state.text}
  
          // Passing a function to child
          updateState={this.handleUpdate}>
        </Child>
      </div>
    );
  }
}
class Child extends Component {
  
  render() {
    return (
      <button 
        // Using parent props to update parent state
        onClick={() => this.props
            .updateState('parent state changed')}>
        {this.props.text}
      </button>
    )
  }
}
  
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: You will see the following button on the screen:

Before Click

After clicking on the button, the following will be the output:

After Click

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!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments