Skip to content

Instantly share code, notes, and snippets.

@Aberratio
Last active July 7, 2023 11:34
Show Gist options
  • Save Aberratio/dfcebfcb65d8b903ee159521283a804d to your computer and use it in GitHub Desktop.
Save Aberratio/dfcebfcb65d8b903ee159521283a804d to your computer and use it in GitHub Desktop.
useOutsideClick

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.

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>
);
};
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