Skip to content
Advertisement

Create sub-headings in a react dropdown component

I have created a drop down menu using the react component . The code is below:

<Select
    style={{ width: 300 }}
    options={people}
    onChange={this.choosePerson}
    placeholder="Select person">
</Select>

The person object is as follows:

const people = [];
people.push({
  label: 'John'
  value: 'John'
});
people.push({
  label: 'Mary'
  value: 'Mary'
});

I was wondering whether it is possible to have sub-headings within this drop down menu in order to group the people (e.g. Men, Women). I have found it possible when using plain javascript but I can’t seem to find how to do it with the set up I currently have.

Advertisement

Answer

I finally managed to achieve it like this:

<Select defaultValue="Select Person" onChange={this.selectPerson} style={{ width: 300 }}>
    <OptGroup label="Man">
    {
      this.state.men.map(function(man) {
          return (<Option key = {man.value}> {man.label}</Option>);
      })
    }
    </OptGroup>
    <OptGroup label="Women">
       {
        this.state.women.map(function(woman) {
            return (<Option key = {woman.value}> {woman.label}</Option>);
         })
    }
    </OptGroup>
</Select>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement