Skip to content

Latest commit

 

History

History
47 lines (35 loc) · 1.36 KB

06.State.md

File metadata and controls

47 lines (35 loc) · 1.36 KB

Jam3 Lessons - React

State

The states are used to reflect the changing data.

We set the initial states in the constructor of the component like this:

class NameForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      name: ''
    };
  }

  handleChange(e) {
    this.setState({ name: e.target.value });
  }

  render() {
    return (
      <form action="?">
        <h3>Welcome { this.state.name }</h3>
        <input onChange={ this.handleChange.bind(this) } placeholder="Your name"/>
        <button type="submit">Continue</button>
      </form>
    );
  }
}

Notice that instead of modifying this.state, we used this.setState method and pass down one or more states we want to change in an object. The only place where you can assign this.state is the constructor.

Also, state updates are asynchronous. That's why is recommended to change states passing down a function.

this.setState((prevState, props) => ({ count: prevState.count + 1 }));

References