Created
April 7, 2020 10:20
-
-
Save LauraBeatris/caf748b652223cd3e71b1d29414ab5cf to your computer and use it in GitHub Desktop.
Custom Hook to toggle Elements. Example: Dropdows
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 { useState, useEffect, useRef } from 'react'; | |
export default () => { | |
const [open, setOpen] = useState(false); | |
const outerNode = useRef(null); | |
function handleClick() { | |
setOpen(!open); | |
} | |
function handleClose(e) { | |
if (outerNode.current.contains(e.target)) { | |
// inside click | |
return; | |
} | |
// outside click | |
setOpen(false); | |
} | |
useEffect(() => { | |
document.addEventListener('mousedown', handleClose); | |
return () => { | |
document.removeEventListener('mousedown', handleClose); | |
}; | |
}, []); | |
return [open, outerNode, handleClick]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment