ideas icon indicating copy to clipboard operation
ideas copied to clipboard

useClickOutside

Open Tomekmularczyk opened this issue 5 years ago • 2 comments

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.

Tomekmularczyk avatar Nov 15 '18 17:11 Tomekmularczyk

May want to pass in ref so that it can be used in other hooks. Here's an example: https://usehooks.com/#useOnClickOutside

gragland avatar Nov 20 '18 17:11 gragland

@gragland yeah, this way it could reuse some existing ref

Tomekmularczyk avatar Nov 20 '18 17:11 Tomekmularczyk