React form error changing a controlled input of type text to be uncontrolled

The underlying problem is that the way I'm setting a property on the shipping object, it does not merge the new property value with the original property values. Therefore the warning wasn't for the TextField that i was EDITING, it was for the other shipping TextFields that were getting blown away. I'm not sure if this is accepted practice since it's hard to find examples where you're working with an object in the state. However, changing the handleShipping method to this fixed my problem:

handleShippingChange(event) {
  var shipping = this.state.shipping;
  shipping[event.target.name] = this.getFieldValue(event.target);

  this.setState({
    shipping: shipping
  });
};

Basically, I'm creating a copy of the existing shipping object from the state, altering it and setting the entire shipping object equal to the altered copy.


Controlled/Uncontrolled input means if the <input> field has a value or not.

// This is a controlled input
<input value="foo"/>

// This is an uncontrolled input
<input value={null}/>

The idea is that you don't want to change from a controlled to an uncontrolled input. Both types of input acts differently and this could potentially lead to bugs and/or inconsistency.

The easiest fix is to ensure there's always a default value (in the case of an empty field, the default would be an empty string '').

Also, note that consistent types are usually better than nullable types given you have a guarantee on the type of a certain value. This helps a lot in reducing overhead due to null checks (if (val != null) { /* ...etc */ })

But if you just want a one line fix, you can also provide the default value inline in jsx:

<input value={value || ''}/>

I just encountered the same issue but it turns out the error was something much simpler (borderline embarrassing).

I forget to add the event parameter when I define my onChange function.

handleChange(event) {
  ...          ^-this
};

Strange that I didn't get a event is undefined error... Hope this helps someone.

Tags:

Reactjs