Skip to content

Instantly share code, notes, and snippets.

@vidaaudrey
Forked from andrei-cacio/click-outide.jsx
Created March 21, 2019 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vidaaudrey/be4ee2631459560fecf18667ec8c6d73 to your computer and use it in GitHub Desktop.
Save vidaaudrey/be4ee2631459560fecf18667ec8c6d73 to your computer and use it in GitHub Desktop.
Clickoutside updated
import React, { Component, useEffect, useCallback } from "react";
function ClickOutsideH({ children, onClick }) {
const refs = React.Children.map(children, () => React.createRef());
const handleClick = useCallback(e => {
const isOutside = refs.every(ref => {
return !ref.current.contains(e.target);
});
if (isOutside) {
onClick();
}
}, []);
useEffect(() => {
document.addEventListener("click", handleClick);
return function() {
document.removeEventListener("click", handleClick);
};
}, []);
return React.Children.map(children, (element, idx) =>
React.cloneElement(element, { ref: refs[idx] })
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment