Skip to content

Instantly share code, notes, and snippets.

@bardouni
Created December 3, 2018 16:01
Show Gist options
  • Save bardouni/c540b27f227bea5ac13d8a09185775e1 to your computer and use it in GitHub Desktop.
Save bardouni/c540b27f227bea5ac13d8a09185775e1 to your computer and use it in GitHub Desktop.
You can use this gift to easily create a toggle system.
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