Controlled and Uncontrolled components

References

Uncontrolled Components – React Official docs https://reactjs.org/docs/uncontrolled-components.html

Controlled Components – React Official docs https://reactjs.org/docs/forms.html#controlled-components

Controlled and uncontrolled form inputs in React don't have to be complicated https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/

Uncontrolled components

An uncontrolled component keeps the source of truth in the DOM. A good example for this, are inputs.

Take this example for instance:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={(input) => this.input = input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Here, the code relies of the value of the input in the DOM rather than in its component state.

Note:

In most cases, it's recommend to use controlled components to implement forms.

Controlled components

In a controlled component, the data are handled by the React component and is usually stored in its state.

Here is the same above example with a controlled component:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

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

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Take the time to look at the other example of the React official documentation:

Last updated