I want to have optgroups in my react-select list, but it doesn't seem to be documented anywhere. I have the following structure, which I pulled from a comment in https://github.com/JedWatson/react-select/issues/59:
render() {
const options = [
{
label: "Group 1",
children: [
{ label: "Group 1, option 1", value: "value_1" },
{ label: "Group 1, option 2", value: "value_2" }
]
},
{ label: "A root option", value: "value_3" },
{ label: "Another root option", value: "value_4" }
];
return <Select options={options} />
}
I expect "Group 1" to be an optgroup, with options 1 and 2 as children. Instead, "Group 1" just appears as a regular option. Does anyone know what the correct key is, within "Group 1", to turn it into an optgroup?
I've already tried "children", and "values", but to no effect.
To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element.
js import React from 'react'; import Select from 'react-select'; ... With those two packages imported, we will be able to have access to the react-select ( <Select />) and also extend the React. Component class. In traditional HTML, the <select> tag houses multiple options and values.
options is the magic key:
render() {
const options = [
{
label: "Group 1",
options: [
{ label: "Group 1, option 1", value: "value_1" },
{ label: "Group 1, option 2", value: "value_2" }
]
},
{ label: "A root option", value: "value_3" },
{ label: "Another root option", value: "value_4" }
];
return <Select options={options} />
}
This renders the way that I expect.
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