React : Updating Component State using setState

In this article, we will see how to update Component State in React.

Updating Component State in React

In React, we can initialize state of a Component in the constructor using this.state.

If we need to change the component’s state, we can do the same using setState() method. It takes key-value pairs as arguments, where keys represent the state properties and values represented updated state data.

Syntax :


this.setState({
// Update state data here
})

For example, to update “name” property in state, we can use :


this.setState({
 name : 'Jane'
})

Example Updating Component State in React

Here is a complete example, where on click of the button, state property “name” is updated.

class Hello extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name : 'John'
        }
        this.handleBtnClick = this.handleBtnClick.bind(this)
      }
      handleBtnClick(){
        this.setState({
            name:"Jane"
        });
      }
  render() {
    return (
      <div className="helloContainer">
        <div>
        <button onClick={this.handleBtnClick}>Update Name</button>
        <h1>Name : {this.state.name}</h1>
      </div>
      </div>
    );
  }
}

Output :

Initial UI :
react update state

On click of Update Name button :
react update state property
 

© 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags