Skip to content

Instantly share code, notes, and snippets.

@hiro08gh
Created April 5, 2020 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiro08gh/f683cdb8fcb371166c31c2d66ed76053 to your computer and use it in GitHub Desktop.
Save hiro08gh/f683cdb8fcb371166c31c2d66ed76053 to your computer and use it in GitHub Desktop.
import useClickOutside from './useClickOutside';
const Menu = () => {
const menuRef = useRef();
const onClickOutside = () => {
console.log('click');
}
useClickOutside(menuRef, onClickOutside)
return (
<div ref={menuRef}>
todo
</div>
)
}
import React, {useEffect} from 'react';
const useClickOutside = (elRef, callback) =>{
useEffect(() => {
const handleClickoutside = e => {
if (elRef?.current?.contains(e.target) && callback) {
callback(e);
}
}
document.addEventListener('click', handleClickoutside, true)
return () => {
document.removeEventListener('click', handleClickoutside, true);
}
}, [callback, elRef])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment