Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useClickOutside #55

Open
Tomekmularczyk opened this issue Nov 15, 2018 · 2 comments
Open

useClickOutside #55

Tomekmularczyk opened this issue Nov 15, 2018 · 2 comments

Comments

@Tomekmularczyk
Copy link

Tomekmularczyk commented Nov 15, 2018

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.

@gragland
Copy link

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

@Tomekmularczyk
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants