Search code examples
reactjshidepanelreact-select

React-select: how to close panel?


I have a react-select instance with a custom option component. When I select an option, the panel doesn't close. I have to click outside the select to make it happen. Is there any kind of global prop I can use? For exemple in Reakit there is popover.hide(). I don't see anything like this in React-select when console logging the props.

Here is my code:

const CustomOption = ({children, onSelect, ...props}) => {
  return (
    <div>
      {children}
          <Chip
            label="SELECT ME"
            onClick={() => onSelect(props.data)}
          />
    </div>
  );
};

const MySelect = ({onSelect) => {
  const customOption = {
    Option: ({ children, ...props }) => <CustomOption {...{children, onSelect, ...props}} />};

  return (
        <Select
          isClearable={true}
          options={availableChoices}
          components={customComponents}
        />
  );
};

Thanks!


Solution

  • Here is the solution: when you use custom components in React-Select, you need to pass the ref as well. So:

    const CustomOption = ({children, onSelect, innerRef, innerProps, ...props}) => {
      return (
        <div ref={innerRef} {...innerProps}>
          {children}
              <Chip
                label="SELECT ME"
                onClick={() => onSelect(props.data)}
              />
        </div>
      );
    };
    
    const MySelect = ({onSelect) => {
      const customOption = {
        Option: ({ children, innerRef, innerProps,...props }) => <CustomOption {...{children, onSelect, innerRef, innerProps, ...props}} />};
    
      return (
            <Select
              isClearable={true}
              options={availableChoices}
              components={customComponents}
            />
      );
    };