I have a simple React component which gets an initial state:
this.state = {
currentObject: {
isYounger: false
}
}
I then render a react-select
with the default value of this.state.currentObject.isYounger
:
<Select
name={"age"}
value={this.state.currentObject.isYounger}
onChange={newValue => this.addIsYoungerValue(newValue)}
options={isYoungerOptions}
/>
For some reason, the value is not set. Why is this?
Codesandbox
Version:
"react-select": "^2.4.2",
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.
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 handle the onChange event on a select element in React: Set the onChange prop on the select element. Keep the value of the selected option in a state variable. Every time the user changes the selected option, update the state variable.
There is an alternate way to use value as your defaultValue. In my case I have used "id" and "industry" instead of "label" and "value"
this.state = {
interested_industries: [{id:"ANY", industry:"ANY"}]
}
And in Select component:-
<Select
name="interested_industries"
options={industries}
value={interested_industries}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={this.handleSelect}
isMulti
/>
Here the issue is not with state selection, the actual issue is that the label is not getting displayed.
So, as per your addIsYoungerValue
function you are setting the value of this.state.currentObject.isYounger
to whole object. i.e. { value: true, label: "Younger" }
. So, the issue can be solved by changing the value of initial state by below.
this.state = {
array: [],
currentObject: {
isYounger: { value: true, label: "Younger" }
}
};
And hurrey, the default value label will be shown..
Your defaultValue
or value
must be objects. In your case like this:
defaultValue={isYoungerOptions[0]}
or
this.state = {
array: [],
currentObject: {
isYounger: { value: "true", label: "Younger" }
}
};
Here an live example.
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