Created
December 3, 2018 16:01
-
-
Save bardouni/a6de27f0f7bebfb1617aa020db27ec14 to your computer and use it in GitHub Desktop.
You can use this gift to easily create a toggle system using ( React Hooks )
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
function useToggle(event = 'click') { | |
let ref = React.useRef(); | |
function close() { | |
// console.log('call close') | |
if(ref.current){ | |
ref.current.style.display = "none"; | |
} | |
document.removeEventListener(event, close); | |
} | |
function onClick() { | |
ref.current.style.display = ""; | |
document.addEventListener(event, close); | |
} | |
React.useLayoutEffect(function () { | |
ref.current.style.display = 'none'; | |
}, []); | |
return [ref, onClick]; | |
} | |
function Component() { | |
let [ref, onClick] = useToggle(); | |
return ( | |
<div> | |
<span onClick={onClick} >toggle</span> | |
<div ref={ref} >content</div> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment