Using material-ui autocomplete with dividers

Viewed 1249

Is there a way to add dividers between material-ui autocomplete options ?

I found only this workaround, but I don't think it's the best way to do it:

const options = [
    {
      label: 'Opt 1',
      value: 'OPT1'
    },
    {
      label: 'Divider',
      value: 'DIV',
      isDivider: true
    },
    {
      label: 'Opt 2',
      value: 'OPT2'
    },
    {
      label: 'Opt 3',
      value: 'OPT3'
    }
  ];

...

  // used to remove the opacity of disabled items (in my case dividers)
  autocompleteOption: {
    '&[aria-disabled="true"]': {
      opacity: 1
    }
  }

...

<Autocomplete
    options={options}
    multiple
    getOptionLabel={(option) => option.label}
    getOptionSelected={(option, value) => isEqual(value, option)}
    classes={{
      option: classes.autocompleteOption
    }}
    getOptionDisabled={(option) => option.isDivider}
    renderOption={(option) => {
      if (option.isDivider) {
        return <Divider className={classes.divider} />;
      }

      return option.label;
     }}
     ...
 />

  • added isDivider option where I need a divider
  • added getOptionDisabled method to disaled divider options
  • added some styling to remove the opacity of disabled items (dividers in my case)
  • added renderOption to render dividers based on the isDivider prop

Do you have any other ideas ?

Thank you for your time :)

1 Answers

Instead of creating a dummy option, how about tagging options that should be followed by a divider?

For instance, say you want to add a divider between the third and forth option. Set isDivider to true for the third option

options[2].isDivider = true

and then inserting the <Divider /> in the renderOption as follows:

renderOption={(props, option: any) => (
  <>
    <Li {...props}>{option.title}</Li>
    {option.isDivider ? <Divider /> : null}
  </>
)}
Related