Search code examples
reactjssetstate

keep an input field a controlled component


I've a component with a state object initialized like this :

this.state = {
    item: {}
}

item is an object that will be populated from the DB (via API call). Then item.name is connected to a form field like this :

<input type="text" name="name" value={this.state.item.name} />

Everything is OK, but the problem comes when I need to RESET the item object.

I want the resetItem() function below to reset the whole item state object, but when I call it after the form is populated once via the API, the input value doesn't change, it keeps the last value, because the input field was trying to change from a controlled field to uncontrolled.

resetItem(){
    this.setState({ item: {} }); //DOESN't work, the input value is not cleared
}

The only way to get it working is if I clean all the object properties, one by one. Which is not what I want.

resetItem(){
    this.setState({ item: { name: '', address: '' } }); //Works, but it's not what I want
}

Demo : JSFiddle

Any ideas on what I'm doing wrong?

Thank you!


Solution

  • This has something to do with when an input field goes from un-controlled component to a controlled component. When you provide input field with nothing, it defaults to un-controlled component.

    https://jsfiddle.net/69z2wepo/240731/

    To keep a component within controlled, use a simple hack

    <input type="text" value={this.state.item.name? this.state.item.name : ""} />