Skip to content

Instantly share code, notes, and snippets.

@JaysonChiang
Created November 16, 2021 14:41
Show Gist options
  • Save JaysonChiang/a01df90d60e1a1ecb315388321816d71 to your computer and use it in GitHub Desktop.
Save JaysonChiang/a01df90d60e1a1ecb315388321816d71 to your computer and use it in GitHub Desktop.
Implement onFocus/onBlur by onClick
const DropDownList = () => {
const [focus, setFocus] = useState(false);
const ref = useRef(null);
useEffect(() => {
const listener = (event) => {
if ( ref.current && event.target && ref.current.contains(event.target)) {
return;
}
setFocus(false);
};
document.addEventListener('click', listener, { capture: true });
return () => {
document.removeEventListener('click', listener, { capture: true });
};
}, []);
if (focus) {
return (
<div ref={ref}>
<div>Open outside to close</div>
<ul>
<li>option1</li>
<li>option2</li>
<li>option3</li>
</ul>
</div>
);
}
return (
<div onClick={() => setFocus(true)}>
<div>Click to Open</div>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment