Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ant design Select component OptGroup in options prop

Tags:

reactjs

antd

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>
like image 735
danielfrs87 Avatar asked Mar 03 '23 01:03

danielfrs87


1 Answers

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

like image 83
JayCodist Avatar answered Mar 16 '23 17:03

JayCodist