Categories
React Answers

How to create optgroups in react-select?

Spread the love

Sometimes, we want to create optgroups in react-select.

In this article, we’ll look at how to create optgroups in react-select.

How to create optgroups in react-select?

To create optgroups in react-select, we just have to nest the option objects in the options array.

For instance, we write:

import React from "react";
import Select from "react-select";

const options = [
  {
    label: "Group 1",
    options: [
      { label: "Group 1, option 1", value: "value1" },
      { label: "Group 1, option 2", value: "value2" }
    ]
  },
  { label: "A root option", value: "value3" },
  { label: "Another root option", value: "value4" }
];
export default function App() {
  return <Select options={options} />;
}

to create the ‘Group 1’ optgroup with:

{
  label: "Group 1",
  options: [
    { label: "Group 1, option 1", value: "value1" },
    { label: "Group 1, option 2", value: "value2" }
  ]
}

in the options array.

Then we set the options prop to the options array to render the options.

Therefore, we see the ‘Group 1’ option group displayed in the select drop down.

Conclusion

To create optgroups in react-select, we just have to nest the option objects in the options array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *