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?
To set selected value of a select drop down to null with React, we can set the state we use as the value of the value prop of the select drop down to null . to set onChange to a function that calls setSelected to e. target. value which is the selected value if it's truthy.
Controlled Components to Get Dropdown Menu Value in React First, we must set up an event listener on the <select> element and define an event handler. In our example, it takes one argument - e (short for event) and calls the setFruit() function. To set the state with the selected value, we access the e. target.
To set a placeholder to a select tag, we can use the <option> element followed by the disabled and hidden attributes. In the above code, we first set a useState() hook intial-value to default and added a value="default" to the “Choose your car” option so that it acts as placeholder for the select tag.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With