How can I create nested option groups in React Select (V2)?

痞子三分冷 提交于 2020-07-09 08:41:27

问题


In React-Select V2, we're able to create option groups by passing an options param like so:

options = [
    { label: 'Group', options: [
        { label: 'Option 1', value: '1' },
        { label: 'Option 2', value: '2' }
    ]}
]

I need to be able to go another layer deep, something like:

options = [
    { label: 'Group', options: [
        { label: 'Option 1', value: '1' },
        { label: 'Option 2', options: [
            { label: 'Option 2-a', value: '2a' },
            { label: 'Option 2-b', value: '2b' },
        ]}
    ]}
]

Which would display the options "Option 2-a" and "Option 2-b" in a group under "Option 2". The approach above doesn't work out of the box, so I want to know if there's a way to create nested groups in React-Select V2.


回答1:


For anyone who comes here with a similar need, I implemented this recursive work-around.

const renderNestedOption = (props, label, nestedOptions) => {
  const {
    cx,
    getStyles,
    innerProps,
    selectOption,   
  } = props;

  // Will be applied to nested optgroup headers 
  const nestedLabelClassName = cx(
    css(getStyles('groupHeading', props)),
    { option: true },
    'nested-optgroup-label',
  );    

  return (
    <div className="nested-optgroup">
      <div className={nestedLabelClassName}>
        {label}
      </div>
      {nestedOptions.map((nestedOption) => {
        if (nestedOption.options) {
          // Read below
          // Read above
          return renderNestedOption(props, nestedOption.label, nestedOption.options);
        }

        const nestedInnerProps = innerProps;
        nestedInnerProps.onClick = () => selectOption(nestedOption);
        return (
          <div className="nested-optgroup-option" key={nestedOption.value}>
            <components.Option {...props} innerProps={nestedInnerProps}>
              {nestedOption.label}
            </components.Option>
          </div>
        );
      })}
    </div>   
  ); 
};

const Option = (props) => {
  const {
    children,
    data,
  } = props;
  const nestedOptions = data.options;

  if (nestedOptions) {
    const label = data.label;
    return renderNestedOption(props, label, nestedOptions);
  }

  return (
    <components.Option {...props}>
      {children}
    </components.Option>
  );
};

Then in your select component, replace the Option component with the custom Option component we just created.

EDIT

There's an open pull request to support this functionality: https://github.com/JedWatson/react-select/pull/2750



来源:https://stackoverflow.com/questions/53119912/how-can-i-create-nested-option-groups-in-react-select-v2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!