How to create a Select dropdown Option Group in React

Cover Image for How to create a Select dropdown Option Group in React

Grouping similar options within a dropdown makes it easier for users to make an appropriate selection. The HTML Option Group Element, <optgroup>, makes this possible.

Here's a quick reference and example for developers working to incorporate option groups into their React dropdowns.

Create a React dropdown using the Select element

This approach requires you to build a React dropdown component using the HTML Select element.

Here's a simple React dropdown component built using the Select element:

const dropdownOptions = [
  { id: 1, name: 'Grapefruit' },
  { id: 2, name: 'Apple' },
  { id: 3, name: 'Orange' },
  { id: 4, name: 'Kiwi'},
  { id: 5, name: 'Carrot' },
  { id: 6, name: 'Potato' },
  { id: 7, name: 'Kale' },
]

const ReactSelectDropdown = ({ options = dropdownOptions }) => {
  // Set the initial selected item to the first dropdown option
  const initialOptionId = options[2].id
  const [selectedOption, setSelectedOption] = useState(initialOptionId);

  const handleDropdownChange = (event) => {
    const optionId = event.target.value;

    setSelectedOption(optionId);
  }

  return (
    <select value={selectedOption} onChange={handleDropdownChange}>
      {
        options.map(({ id, name }) => {
          return (
            <option key={name} value={id}>{name}</option>
          );
        })
      }
    </select>
  );
}

Live Example

Here's a live example of what the above <ReactSelectDropdown /> renders as:

The above example groups fruits and vegetables as dropdown items without any distinction or grouping. As we only have a handful of items in our dropdown, the user experience is manageable. But, what if we had a dropdown with 10 or 20 additional options?

Let's use option group elements to create unique groupings within the Select dropdown.

Add option groups to our React Select dropdown

const dropdownOptionsWithOptionGroups = [
  { id: 1, name: 'Grapefruit', optionGroup: 'fruit' },
  { id: 2, name: 'Apple', optionGroup: 'fruit' },
  { id: 3, name: 'Orange', optionGroup: 'fruit' },
  { id: 4, name: 'Kiwi', optionGroup: 'fruit' },
  { id: 5, name: 'Carrot', optionGroup: 'vegetable' },
  { id: 6, name: 'Potato', optionGroup: 'vegetable' },
  { id: 7, name: 'Kale', optionGroup: 'vegetable' },
]

const ReactSelectDropdownWithOptionGroups = ({ options = dropdownOptionsWithOptionGroups }) => {
  // Set the initial selected item to the first dropdown option
  const initialOptionId = options[2].id
  const [selectedOption, setSelectedOption ] = useState(initialOptionId);
  
  const handleDropdownChange = (event) => {
  const optionId = event.target.value;
    setSelectedOption(optionId);
  }
  
  const groupedOptions = options.reduce((acc, option) => {
    const accOptionGroup = acc[option.optionGroup] || [];
      
    return {
      ...acc,
      [option.optionGroup]: [...accOptionGroup, option]
    }
  }, {});
    
  return (
    <select value={selectedOption} onChange={handleDropdownChange}>
      { 
       Object.keys(groupedOptions).map((optionGroupName) => (
          <optgroup key={optionGroupName} label={optionGroupName}>
            {
              groupedOptions[optionGroupName].map(({ id, name }) => (
                <option key={name} value={id}>{name}</option>
              ))
            }
          </optgroup>
        ))
      }
    </select> 
  );
}

Live Example

Above is a live example of the previous React component.

You should note the above dropdown includes separate select option groups for "fruits" and "vegetables." This visual grouping helps break up long dropdown lists, making it easier for users to make the appropriate selection.

References

Check out these resources for additional information and learnings: