gravity-ui / uikit

https://gravity-ui.com
MIT License
582 stars 89 forks source link

renderSelectedOption for multiselect control #1568

Open danonechik94 opened 5 months ago

danonechik94 commented 5 months ago

The scenario is as follows: I have several multiselect controls and I want to render the selected values in the control a little bit differently, compared to the default comma join. In one control I want to render selected options joined with "and" and in other controls, I would like to render the "All {type}" ("All ticket types", for example).

By default, you can only render selected options one by one with the renderSelectedOption prop. But this function lacks a scenario with the multiselect. I think this scenario should be built-into the control, for example, with an override of the renderSelectedOption function for the multiselect scenario.

I implemented a workaround for a controlled input, but it is not going to work for an uncontrolled one. The idea is to render all the required items in the first call of the renderSelectedOption callback and render an empty string in other calls:

export const MyCustomFilter = ({options, value, renderSelectedOptions}) => {
  const renderSelectedOptionHandler = (_, index) => {
      if (index > 0) {
        return '' as unknown as ReactElement;
      }
      return <Text>{renderSelectedOptions(value, filter.items)}</Text>;
    }) satisfies SelectProps['renderSelectedOption'];

  return (
    <Select
      renderSelectedOption={renderSelectedOptionHandler}
      value={value}
      ...
    >
      {items.map((props) => (
        <Select.Option {...props} />
      ))}
    </Select>
  );
};
korvin89 commented 5 months ago

@danonechik94 Here is my suggestion: