Prevent select from closing after choosing a value

7.2k views Asked by At

I have created a custom dropdown menu in Javascript React using the react-select component. By using the optionComponent prop I was able to render each option with a checkbox (see image). My problem is now that once you click any checkbox the select options close which is not a very good user experience.

Image:

enter image description here

Therefore my question is if there is any way of preventing the drop-down from closing until the user clicks the arrow in the right-hand side of the select to make it possible to tick and untick any number of check boxes before closing down the options.

2

There are 2 answers

0
Daniel Andrei On

You could stopPropagation of the click event from the checkbox element.

Let's assume this is your checkbox click handler:

onClickHandler = (e) => {
    e.stopPropagation();
    //do some other logic
}

This way, when the checkbox is clicked, it will not trigger the select handler on the dropdown.

0
Akis On

For anyone who is trying to stop do the e.stopPropagation() and still isn't working, a workaround I found is to set the z-index: -1 to my custom component. That has the result to put my component below the row that react-select is creating, so my component looks like is clicked, but what really does is to listen to the click on the row. Also this solves the main issue that it will not close the list popup

Example:

      <components.Option
        {...rest}
        isDisabled={isDisabled}
        isFocused={isFocused}
        isSelected={isSelected}
        innerProps={props}
      >
        <CustomCheckbox
          isSelected={isSelected}
          isDisabled={isDisabled}
          style={{ zIndex: '-1' }} // Easiest possible fix for the issue when clicking on a custom element would dismiss the list Popup.
        >
          <div className={'px-6 text-t-primary'}>{children}</div>
        </CustomCheckbox>
      </components.Option>