How To Close A Dropdown When Click Outside In React

-In this article, we will learn how to close a modal when clicking outside in react.

-First, open the react project and then add the below styles in index.css.
-Here we are adding some CSS for the button.

-index.css:

body {
  margin: 0 auto;
  max-width: 500px;
}
.wrapper {
  display: inline-flex;
  flex-direction: column;
}

.button {
  margin: 20px 0px 0px 0px;
  border: 1px solid red;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bolder;
  background-color: whitesmoke;
  width: 140px;
  color: black;
}

.list {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  border: 1px solid #ccc;
  list-style-type: none;
  padding: 0;
  margin: 0;
  width: auto;
  display: inline-block;
}
.list-item {
  padding: 8px;
  cursor: pointer;
  background-color: whitesmoke;
}
.list-item:hover,
.list-item:active {
  background-color: #f3f3f3;
}

-Then add the below code in the App.js file for creating the button and dropdown list.
-Dropdown will be displayed when we click on the button.

–App.js:

import { useEffect, useRef, useState } from "react"

function App() {
  const ref = useRef()

  const [isMenuOpen, setIsMenuOpen] = useState(false)

  useEffect(() => {
    const checkIfClickedOutside = e => {
      // If the menu is open and the clicked target is not within the menu,
      // then close the menu
      if (isMenuOpen && ref.current && !ref.current.contains(e.target)) {
        setIsMenuOpen(false)
      }
    }

    document.addEventListener("mousedown", checkIfClickedOutside)

    return () => {
      // Cleanup the event listener
      document.removeEventListener("mousedown", checkIfClickedOutside)
    }
  }, [isMenuOpen])

  return (
    <div className="wrapper" ref={ref}>
      <button
        className="button"
        onClick={() => setIsMenuOpen(oldState => !oldState)}
      >
        Click Me
      </button>
      {isMenuOpen && (
        <ul className="list">
          <li className="list-item">dropdown option 1</li>
          <li className="list-item">dropdown option 2</li>
          <li className="list-item">dropdown option 3</li>
          <li className="list-item">dropdown option 4</li>
        </ul>
      )}
    </div>
  )
}

export default App

-in this app.js file we use a contains so we can easily identify whether a targeted not is inside a particular node or not.
-so if the click is inside the node it returns a true otherwise false.

Output:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories