Created
November 16, 2021 14:41
-
-
Save JaysonChiang/a01df90d60e1a1ecb315388321816d71 to your computer and use it in GitHub Desktop.
Implement onFocus/onBlur by onClick
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
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