Last active
April 11, 2019 16:25
-
-
Save gengue/74ce7521e3a9ac147618aaefb24fdc9a to your computer and use it in GitHub Desktop.
React component: detect when focus has been lost
This file contains hidden or 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
import React, { useRef, useEffect } from 'react'; | |
/** | |
* Example: | |
* const [open, setOpen] = useState(false); | |
* ... | |
* <ClickOutside onBlur={() => setOpen(false)}> | |
* <MyDropdown open={open}/> | |
* </ClickOutsie> | |
*/ | |
function ClickOutside({ children, onBlur }) { | |
/* Set the wrapper ref */ | |
const wrapperRef = useRef(null); | |
/* Alert if clicked on outside of element */ | |
const handleClickOutside = event => { | |
if ( | |
wrapperRef && | |
wrapperRef.current && | |
!wrapperRef.current.contains(event.target) | |
) { | |
onBlur && onBlur(); | |
} | |
}; | |
useEffect(() => { | |
document.addEventListener('mousedown', handleClickOutside); | |
return () => document.removeEventListener('mousedown', handleClickOutside); | |
}, []); | |
return <div ref={wrapperRef}>{children}</div>; | |
} | |
export default ClickOutside; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment