What are uncontrolled components?

Technology CommunityCategory: ReactWhat are uncontrolled components?
VietMX Staff asked 3 years ago

The Uncontrolled Component are the one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML For example, in the below UserProfile component, the name input accessed using ref as below,

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

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

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

In most cases, it is recommend using controlled components to implement forms.