Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create optgroups in react-select v2?

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.

like image 355
ouni Avatar asked Sep 25 '18 17:09

ouni


People also ask

How do I create a select option in react?

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.

How do you use react select in react?

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.


1 Answers

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.

like image 64
ouni Avatar answered Oct 05 '22 21:10

ouni