To set the default value of the <select> element, you can use the defaultValue attribute in React. Let's look at a sample code. This controlled component sets the default value using the appropriately named defaultValue attribute on the <select> element.
The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.
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.
I guess you need something like this:
const MySelect = props => (
<Select
{...props}
value = {
props.options.filter(option =>
option.label === 'Some label')
}
onChange = {value => props.input.onChange(value)}
onBlur={() => props.input.onBlur(props.input.value)}
options={props.options}
placeholder={props.placeholder}
/>
);
I used the defaultValue parameter, below is the code how I achieved a default value as well as update the default value when an option is selected from the drop-down.
<Select
name="form-dept-select"
options={depts}
defaultValue={{ label: "Select Dept", value: 0 }}
onChange={e => {
this.setState({
department: e.label,
deptId: e.value
});
}}
/>
If you've come here for react-select v2, and still having trouble - version 2 now only accepts an object as value
, defaultValue
, etc.
That is, try using value={{value: 'one', label: 'One'}}
, instead of just value={'one'}
.
I was having a similar error. Make sure your options have a value attribute.
<option key={index} value={item}> {item} </option>
Then match the selects element value initially to the options value.
<select
value={this.value} />
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