When the state is updated, we want to update the defaultValue of React-Select as well

Viewed 49

I want to display the default value in ReactSelect's defaultValue, but when the state is updated, the defaultValue is not updated. The default display is not updated.

What can I do to avoid this phenomenon? I would appreciate it if you could tell me more about it.

constructor(props) {
        super(props)
        this.state = {
            item: props.item,
        };
    }

const set = { label: this.state.item.name, value: this.state.item.id }

<Select
    options={groupOptions}
    defaultValue={set}
/>
3 Answers

I believe defaultValue is your initial value. To update you need to pass the new set to value

<Select
    options={groupOptions}
    defaultValue={set}
    value={set}
    />

you're just missing the value prop , also you need the onChange prop

<Select
    options={groupOptions}
    defaultValue={set}
    value={set}
    onChange={e=>{
        const value =e.target.value
        //set state here 
     }}
/>

Pass value as prop.

Here is the code:

    <Select
      name="something"
      options={groupOptions}
      defaultValue={set}
      value={set}
      onChange={(e) => inputChangeHandler(e.target.value)}
    />

Note: inputChangeHandler function will update the state.

Happy coding :)

Related