Skip to content

Instantly share code, notes, and snippets.

@chamatt
Created July 15, 2020 23:01
Show Gist options
  • Save chamatt/d61eb8cf00c57a96255259aa94e99f2f to your computer and use it in GitHub Desktop.
Save chamatt/d61eb8cf00c57a96255259aa94e99f2f to your computer and use it in GitHub Desktop.
Close on click outside in react (for custom dropdown components)
const CustomDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const handleBlur = e => {
const currentTarget = e.currentTarget;
setTimeout(() => {
if (!currentTarget.contains(document.activeElement)) {
setIsOpen(false);
}
}, 0);
};
<div tabIndex="0" onBlur={handleBlur}>
// Your custom dropdown goes here
</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment