React State

React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders. State is similar to props, but it is private and fully controlled by the component.

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "Folau"
    };
  }
  render() {
    return (
      <div>
        <h1>My name is {this.state.name}</h1>
      </div>
    );
  }
}

Change state

To change a value in the state object, use the this.setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s). 

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "Folau"
    };
  }
  changeName = () => {
    this.setState({name: "Lisa"});
  }
  render() {
    return (
      <div>
        <h1>My name is {this.state.brand}</h1>
        <button
          type="button"
          onClick={this.changeName}
        >Change Name</button>
      </div>
    );
  }
}

Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods).

Don’t change state directly

this.state.comment = 'Hello';




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.