DEV Community

muneebejazz
muneebejazz

Posted on

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

Top comments (0)