Skip to content

Instantly share code, notes, and snippets.

@smitpatelx
Created January 11, 2021 20:38
Show Gist options
  • Save smitpatelx/3f6ddbfc6db5dbde73ec86ac36db072e to your computer and use it in GitHub Desktop.
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!
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