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

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging β†’

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay