I have the following code as part of my React component:
When setting the value for your select component, you will have to convert null
to ''
; and when receiving the value from your component, you will have to convert ''
to null
. A simple example:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { selected: null };
}
render() {
return <div>
<select
className="input form-control"
onChange={e => this.setState({ selected: e.target.value || null })}
value={this.state.selected || ''}>
<option value=''></option>
<option value='1'>cook dinner</option>
<option value='2'>do dishes</option>
<option value='3'>walk dog</option>
</select>
<input type='button' onClick={() => this.setState({ selected: null })} value='Reset' />
</div>
}
}
This works assuming that your ids are always truthy: e.target.value || null
will convert the selected empty string to null
; and this.state.selected || ''
will convert your null
state to an empty string. If your ids can be falsey (for example the number 0
), you will need a more robust conversion.
See Fiddle here.
I think your problem might be caused by this line:
value={task.user_id}
The select will always show that as a value regardless of what was selected.
If your onUserChanged function is right you should see the right value in being selected on the server or on the console, but the client will always see that task.user_id.
Otherwise everything else seems right in your code.