Reputation: 373
Is there a way to declare 'selected' in options array, and this 'selected' item will be displayed by default?
<Select onChange={this.changeUser}
options={[{value:1,labe:1},
{value:2,label:2,selected},
{value:3,label:3}]}
/>
Upvotes: 4
Views: 11721
Reputation: 933
As stated in the docs you can set a default selected value as value
in state which you can update when the user switches to an alternate option using the onChange
handler
Take a look at this example from the docs
import React from 'react';
import Select from 'react-select';
class App extends React.Component {
state = {
selectedOption: {value: 'one', label: 'One'},
}
handleChange = (selectedOption) => {
this.setState({ selectedOption }); // this will update the state of selected therefore updating value in react-select
console.log(`Selected: ${selectedOption.label}`);
}
render() {
const { selectedOption } = this.state;
const value = selectedOption && selectedOption.value; // this will read from state and set the value in state as the selected value. Therefore setting a value even when none has yet to be selected.
return (
<Select
name="form-field-name"
value={value} // so here the default value of one will be set then updates during the on change event
onChange={this.handleChange}
options={[
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
]}
/>
);
}
}
Set a selected value in the state
the set the value of this option as the value
in react-select
Upvotes: 2