Last active
March 8, 2019 08:26
-
-
Save andrei-cacio/676b827ad8a27375ddac58c5a32cff54 to your computer and use it in GitHub Desktop.
ClickOutside Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, useEffect } from "react"; | |
function ClickOutside({ children, onClick }) { | |
const refs = React.Children.map(children, () => React.createRef()); | |
const handleClick = 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