# Controlled and Uncontrolled components

![](https://366599030-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEGRfOxS6iFE8GUqpjc%2F-LEGRjwPuGTTScW_73Bs%2F-LEGRpySeBAP0oqKFWSu%2Fcontrolled-vs-uncontrolled-cover.png?generation=1528227390273926\&alt=media)

## 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 `input`s.

Take this example for instance:

```jsx
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:

```jsx
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:

* Textarea tag &#x20;

  <https://reactjs.org/docs/forms.html#the-textarea-tag>
* Select tag &#x20;

  <https://reactjs.org/docs/forms.html#the-select-tag>
* Handling multiple inputs &#x20;

  <https://reactjs.org/docs/forms.html#handling-multiple-inputs>
