DEV Community

muneebejazz
muneebejazz

Posted on

4 3

react component dropdown & detect click outside react component

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

const Test = () => {
  const divRef = useRef();
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    function handleDocumentClick(e) {
      if (
        divRef.current &&
        !divRef.current.contains(e.target) &&
        divRef.current !== e.target
      ) {
        setIsOpen(false);
      }
    }

    document.addEventListener("click", handleDocumentClick);

    return () => {
      document.removeEventListener("click", handleDocumentClick);
    };
  }, []);

  return (
    <div>
      <button
        className="px-5 py-2 border border-gray-400 rounded"
        onClick={(e) => {
          e.stopPropagation();
          setIsOpen((prev) => !prev);
        }}>
        English
      </button>
      {isOpen && (
        <div
          ref={divRef}
          className="px-5 py-2 rounded border border-gray-400 rounded flex flex-col gap-3 inline-flex">
          <div>
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Quibusdam
            aut voluptatem reiciendis modi sapiente deleniti quaerat repellat,
            provident ea quas nemo voluptatum cupiditate perferendis iusto earum
            molestiae molestias ratione veniam.
          </div>
          <button>Arabic</button>
          <button>German</button>
        </div>
      )}
    </div>
  );
};

export default Test;

Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay