skip to Main Content

Here I have 3 dropdowns.
When click outside all of 3 dropdowns are closed normally but when I click on the other dropdown the others remain opened when already opened.
The intended behavior is that even when I click on other dropdown it should close whatever dropdown already opened.
How to achieve this?

This is a the demo I’m working on:
https://stackblitz.com/edit/github-mxncy7?file=src%2Findex.css

2

Answers


  1. Use onBlur event to close the dropdown:

    function App() {
      ...
      const handleOnBlur = (e) => {
        e.stopPropagation();
        setIsOpenDropdown(false);
      };
      ...
      return (
        <>
          <div className="dropdown-wrapper"
            tabIndex="0" 
            onBlur={handleOnBlur}
          >
            <div
              className="dropdown-btn"
              onClick={handleClickDropdownButton}
            >
       ...
       );
    }
    

    Full demo on Stackblitz.

    Login or Signup to reply.
  2. Its because its set to handle clicks outside that is the background and the drop down list is a button.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search