React select with value null

Viewed 67172

I have the following code as part of my React component:

<select
  className="input form-control"
  onChange={this.onUserChanged}
  value={task.user_id}>
  <option value=''></option>
  {this.renderUserOptions()}
</select>

When the task.user_id is null on the first rendering of the component, the select is properly displayed with the empty option with value ''.

However, if I change the value from something that has a value back to the default option, the server side updates correctly, the task object returns the null for task.user_id but the select doesn't change to the default value.

What should I do to handle this scenario?


3 Answers

using npm i react-usestateref usestateref
<MenuItem> value using ternary operator condition ? exprIfTrue : exprIfFalse

const [boardvalue, setboardvalue, ref] = useStateRef("");  
const handleChange = (e) => {
    setboardvalue(e.target.value);
  }; 

<Select style={{ flex: 2 ,}} 
disabled={ref.current==="State Board"?false:true} onChange{handleChangeClass} >
    {dataRef.current.allClass.map((text, index) => (
        <MenuItem value={ref.current==="State Board" ? text:""}>{text}</MenuItem>
     ))}
  </Select>
Related