Skip to content

useClickOutside #55

@Tomekmularczyk

Description

@Tomekmularczyk

Based on idea from this article:

export default function Img({ src }) {
  const ref = useClickOutside(handleClickOutside);

  function handleClickOutside() {
    console.log("clicked outside");
  }

  return (
    <img
      ref={ref}
      src={src}
      alt="comment"
    />
  );
}

function useClickOutside(fn) {
  const ref = useRef(null);
  useEffect(() => {
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
  });

  function handleClick(e) {
    if (ref.current.contains(e.target)) {
      return; // inside the element
    }
    fn();
  };

  return ref;
}

It probably doesn't cover some edge cases like React.Protals though.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions