This useOutsideClick
hook takes an array of refs refs
and a callback function callback
. It checks if all the refs in the array are defined and if the click occurred outside of each of those elements. If so, the callback function callback
is called.
Last active
July 7, 2023 11:34
-
-
Save Aberratio/dfcebfcb65d8b903ee159521283a804d to your computer and use it in GitHub Desktop.
useOutsideClick
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
import React, { useRef } from 'react'; | |
import { useOutsideClick } from './useOutsideClick'; | |
export const MyComponent = () => { | |
const ref1 = useRef(null); | |
const ref2 = useRef(null); | |
const handleOutsideClick = () => { | |
// Place your code to be executed when clicked outside the elements | |
}; | |
useOutsideClick([ref1, ref2], handleOutsideClick); | |
return ( | |
<div> | |
<div ref={ref1}> | |
{/* Your code */} | |
</div> | |
<div ref={ref2}> | |
{/* Your code */} | |
</div> | |
</div> | |
); | |
}; |
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
import { useEffect, RefObject } from 'react'; | |
export const useOutsideClick = <T extends HTMLElement>( | |
refs: RefObject<T>[], | |
callback: () => void | |
): void => { | |
useEffect(() => { | |
const handleClickOutside = (event: MouseEvent) => { | |
const isOutsideClick = refs.every((ref) => { | |
return ref.current && !ref.current.contains(event.target as Node); | |
}); | |
if (isOutsideClick) { | |
callback(); | |
} | |
}; | |
const handleEscapeKey = (event: KeyboardEvent) => { | |
if (event.key === 'Escape') { | |
callback(); | |
} | |
}; | |
const handleWindowResize = () => { | |
callback(); | |
}; | |
document.addEventListener('mousedown', handleClickOutside); | |
document.addEventListener('keydown', handleEscapeKey); | |
window.addEventListener('resize', handleWindowResize); | |
return () => { | |
document.removeEventListener('mousedown', handleClickOutside); | |
document.removeEventListener('keydown', handleEscapeKey); | |
window.removeEventListener('resize', handleWindowResize); | |
}; | |
}, [refs, callback]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment