useClickOutside(๐)
#6 hook of the week
To remind you of the purpose and goal of this week:
For a whole week I'll post a new hook every day. All hooks will support Server-Side Rendering (SSR) and have TypeScript implemented.
I will not describe the hooks in great detail, I'll just present them and show how it's implemented. Then you can do whatever you want with them.
Every hook is also available here, together with a range of other hooks.
Showcase ๐ฅ
Every time you click outside the element below I'll increase the number of clicks by one.
The hook ๐ฃ
Trigger a callback when the user clicks outside of a defined element.
I'm using my useEventListener() hook and getRefElement() utility to listen for click events.
import { useCallback, RefObject } from 'react';
import { useEventListener } from './hooks';
import { getRefElement } from './utils';
export const useClickOutside = (
element: RefObject<Element> | null,
callback: (event: MouseEvent) => void
): void => {
const handleClick = useCallback(
(event) => {
if (!getRefElement(element)?.contains(event.target)) {
callback(event);
}
},
[callback, element]
);
useEventListener({
type: 'click',
listener: handleClick
});
};
Usage
When a user clicks outside of the defined ref
element we console.log()
its event.
import React, { useRef } from 'react';
import { useClickOutside } from './hooks';
const Component = () => {
const ref = useRef(null);
useClickOutside(ref, (event) => {
console.log(event);
});
return <div ref={ref} />;
};
export default Component;
The end ๐
I hope you found this helpful.