-->

How do you create optgroups in react-select v2?

2020-06-30 09:21发布

问题:

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.

回答1:

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.