Uncontrolled Components

suggest change

Uncontrolled components are inputs that do not have a value property. Unlike controlled components, the DOM holds the input’s current value, and later updates to component state do not change what the input shows.

class Form extends React.Component {
  constructor(props) {
    super(props);
    
    this.onChange = this.onChange.bind(this);
    
    this.state = {
      name: 'John'
    };
  }
  
  onChange(e) {
    this.setState({
      name: e.target.value
    });
  }
  
  render() {
    return (
      <div>
        <label htmlFor='name-input'>Name: </label>
        <input
          id='name-input'
          onChange={this.onChange}
          defaultValue={this.state.name} />
      </div>
    )
  }
}

Here, the component’s state is updated via the onChange event handler, just as for controlled components. However, instead of a value property, a defaultValue property is supplied. This determines the initial value of the input during the first render. Any later changes to the component’s state are not reflected by the input. If they need to be, use a controlled component instead.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents