Created
January 11, 2021 20:38
-
-
Save smitpatelx/3f6ddbfc6db5dbde73ec86ac36db072e to your computer and use it in GitHub Desktop.
Wrapper for catching blur and click outside event. Useful while building dropdowns and many more!
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 { useState } from "react"; | |
const FocusOutside = ({clickedOutside, ...props})=>{ | |
let _timeoutID; | |
const [IsManagingFocus, setIsManagingFocus] = useState(false); | |
const _onBlur = ()=>{ | |
_timeoutID = setTimeout(() => { | |
if (IsManagingFocus) { | |
setIsManagingFocus(false) | |
clickedOutside() | |
} | |
}, 0); | |
} | |
const _onFocus = ()=>{ | |
clearTimeout(_timeoutID); | |
if (!IsManagingFocus) { | |
setIsManagingFocus(true) | |
} | |
} | |
return ( | |
<div | |
onBlur={_onBlur} | |
onFocus={_onFocus} | |
>{props.children}</div> | |
); | |
} | |
export default FocusOutside; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment