React useClickOutside
import React, {useRef, useState, useEffect} from 'react'
export function useClickOutside<T extends HTMLElement>(callback: () => void): React.RefObject<T> {
let dom = useRef<T>(null);
const handleClick = ({target}: Event) => {
if (target && dom.current && !dom.current.contains(target as Node)) {
callback()
}
}
useEffect(() => {
document.addEventListener("click", handleClick)
return () => {
document.removeEventListener("click", handleClick)
}
}, [])
return dom;
}
export function App() {
const [open, setOpen] = useState(false)
const outsideClickRef:React.RefObject<HTMLElement> = useClickOutside(() => {
setOpen(false)
});
const styles = {
width: '120px',
height: '200px',
border : '2px dashed red'
};
const listStyles = {
display: open ? 'block' : 'none'
}
return <div style={styles}>
<section ref={outsideClickRef}>
<h3 onClick={() => setOpen(true)}>Click to see menu</h3>
<ul style={listStyles}>
<li>menu1</li>
<li>menu2</li>
<li>menu3</li>
<p onClick={() => setOpen(false)}>Close X</p>
</ul>
</section>
</div>
}