How to detect click outside React component?

Sometimes, we want to detect click outside React component.

In this article, we’ll look at how to detect click outside React component.

How to detect click outside React component?

To detect click outside React component, we create our own hook.

For instance, we write

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

export default function useComponentVisible(initialIsVisible) {
  const [isComponentVisible, setIsComponentVisible] =
    useState(initialIsVisible);
  const ref = useRef(null);

  const handleClickOutside = (event) => {
    if (ref.current && !ref.current.contains(event.target)) {
      setIsComponentVisible(false);
    }
  };

  useEffect(() => {
    document.addEventListener("click", handleClickOutside, true);
    return () => {
      document.removeEventListener("click", handleClickOutside, true);
    };
  }, []);

  return { ref, isComponentVisible, setIsComponentVisible };
}

to define the useComponentVisible with the initialVisible parameter.

In it, we define the handleClickOutside that checks if we clicked outside with ref.current && !ref.current.contains(event.target).

If we did, then we set isComponentVisible to false.

And we use that as the click handler for document.

Then we use it by writing

const DropDown = () => {
  const { ref, isComponentVisible } = useComponentVisible(true);
  return <div ref={ref}>{isComponentVisible && <p>Dropdown Component</p>}</div>;
};

to get the ref returned by useComponentVisible.

If isComponentVisible is true, then we render the p element.

Conclusion

To detect click outside React component, we create our own hook.