How do you create optgroups in react-select v2?

2020-06-30 08:46发布

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条回答
贪生不怕死
2楼-- · 2020-06-30 09:11

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.

查看更多
登录 后发表回答