Controlled and uncontrolled form input in React

You’ve probably seen many articles that say, “You shouldn’t use itsetState“,”refsIs not good “, this is contradictory, so what are the criteria for choosing? How can we do this well? It can be said that forms are at the heart of a Web applicationreactForm processing is also important. The following is a description of the differences between the two processes and the scenarios in which they are used.

uncontrolled

Uncontrolled input is like traditional 'HTML' form inputCopy the code
class Form extends Component{
    render(){
        <div>
            <input type="text"/>
        </div>}}Copy the code

They remember what you type. And then you can use ref to get their values,

class Form extends Component {
  handleSubmitClick = () = > {
    const name = this._name.value;
    // do something with `name`
  }

  render() {
    return (
      <div>
        <input type="text" ref={input= > this._name = input} />
        <button onClick={this.handleSubmitClick}>Sign up</button>
      </div>); }}Copy the code

In other words, you have to get values from the form when you need them. This is the easiest way to perform form input. But again, it’s not that powerful.

controlled

A controlled input takes its current value and a callback that changes that value. You could say it’s a “React way” (that doesn’t mean you should use it all the time).

<input value={someValue} onChange={handleChange} />
Copy the code

But the input value must exist in some state. Normally, the component that renders the input (that is, the form component) stores its state:

class Form extends Component {
  constructor() {
    super(a);this.state = {
      name: ' '}; } handleNameChange =(event) = > {
    this.setState({ name: event.target.value });
  };

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.name}
          onChange={this.handleNameChange}
        />
      </div>); }}Copy the code

HandleNameChange is called each time a new character is entered. It accepts the new value entered and sets it to state.

The form component always gets the latest value, which means your data is in sync with your UI, which means the form component can immediately respond to changes in input. Here are some scenarios where this approach is commonly used

  • In-place feedback, such as form validation
  • Disable button, all data is valid data
  • Enforce specific input formats, such as credit card numbers

Of course, if you think it would be easier to go uncontrolled, go for uncontrolled!

How do I keep elements under control

Of course, there are other form elements. Check boxes, checkboxes, text areas. If you set the value of a form element with a prop, it becomes “controlled.” However, each form element has a different tool for setting values

The element value Change the callback A new position in a callback
<input type="text" /> value=”string” onChange event.target.value
<input type="checkbox" /> checked={boolean} onChange event.target.checked
<input type="radio" /> checked={boolean} onChange event.target.checked
<textarea /> value=”string” onChange event.target.value
<select /> value=”option value” onChange event.target.value

conclusion

There are advantages to both controlled and uncontrolled forms fields. Evaluate your situation and choose the right approach — what works for you is enough. If your form is very simple in terms of UI feedback, uncontrolled reference is perfectly fine. You don’t have to listen to all sorts of articles about what’s “bad.”

scenario uncontrolled controlled
One-time value retrieval
Validation at submission
Instant form validation fields
Conditionally disable the submit button
Force format input
Multiple inputs for one piece of data
Dynamic input

Controlled and uncontrolled form inputs in React don’t have to be complicated