49

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.

ouni
  • 3,233
  • 3
  • 15
  • 21
  • 6
    It is actually documented at https://react-select.com/props#groupheading under GroupType. – ouni Sep 25 '18 at 18:02

1 Answers1

111

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.

ouni
  • 3,233
  • 3
  • 15
  • 21
  • According to the docs I linked to in the OP comment, this is still valid; was there a specific thing that wasn't working? – ouni Mar 21 '20 at 21:45
  • how can I get selected group label and label and value of option selected ? – Kalyan A Jun 28 '20 at 11:33
  • I mean to say how can I get "Group 1" if I select Group 1,option 1 – Kalyan A Jun 28 '20 at 11:47
  • @Kalyan If your code has the items categorized for the select, I would think you could easily detect to which group an item belongs, outside the context of react-select. In any case, if you still have trouble, you should always ask in a new question. – Anj Aug 14 '20 at 10:52