danielfrs87
danielfrs87

Reputation: 127

Ant design Select component OptGroup in options prop

Is it possible to add OptGroup to options prop in Select component from Ant Design (https://ant.design/components/select/)?

import React from 'react';
import { Select } from 'antd';

const Places = () => {
  function handleChange(value, objectValues) {
    console.log(value);
    console.log(objectValues);
  }
return (
 <>
    <Select
      labelInValue
      defaultValue={{ value: 'Lucy' }}
      style={{ width: 120 }}
      onChange={handleChange}
      options={[ // add OptGroup here ??
        { label: 'Jack', value: 'Jack', id: '1' },
        { label: 'Lucy', value: 'Lucy', id: '2' },
      ]}
     />
  </>
  );
  };

export default Places;

instead of doing it like this the traditional way, I want to add the OptGroup to the options prop.

<Select defaultValue="lucy" style={{ width: 200 }} onChange={handleChange}>
 <OptGroup label="Manager">
  <Option value="jack">Jack</Option>
  <Option value="lucy">Lucy</Option>
 </OptGroup>
</Select>

Upvotes: 6

Views: 8149

Answers (1)

JayCodist
JayCodist

Reputation: 2544

Actually, yes you can! Just pass in an object with label and options properties. Like this:

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select
      labelInValue
      defaultValue={{ value: 'Lucy' }}
      style={{ width: 120 }}
      onChange={handleChange}
      options={[
          {
            label: "Test",
            options:
            [
              { label: 'Jack', value: 'Jack', id: '1' },
              { label: 'Lucy', value: 'Lucy', id: '2' }
            ]
          }
      ]}
     />,
  mountNode,
);

Here's a working pen

Upvotes: 14

Related Questions