is value attribute necessary in a react component's input?

Viewed 747

My Register component:

const Register = () => {
  const [name, setName] = useState('');
  const onNameChange = (e) => {
    setName(name = e.target.value);
  };
<form className="form" onSubmit={onFormSubmit}>
    <div className="form-group">
      <input
        type="text"
        placeholder="Name"
        name="name"
        value={name}
        onChange={onNameChange}
        required
      />
    </div>
    </form>

My question is what is the purpose of putting the value attribute i.e "value={name}"?

I noticed that even without writing it(the value attribute), the value(e.target.value) is taken as whatever is over the said <input>. It seems to me that it functions the same without the value attribute.

1 Answers

Setting a value attribute isn't necessary, but it's usually a good idea. Putting a value attribute makes the input controlled, which means that the value in the input will always exactly correspond to what's in the React state, which will make the program's logic easier to reason about.

With a controlled input, if you ever need to set the value to something other than what the user has typed in, you just need to call setName with the value to set, and the input will receive that new custom value.

If you use an uncontrolled component (one without a value), you'll probably want to use a ref to get the value (since having name / setName as stateful doesn't really provide a benefit anymore).

Related