-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Dorien Grönwald
committed
Jun 5, 2024
1 parent
5f5ac5e
commit d565db0
Showing
2 changed files
with
16 additions
and
11 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,23 @@ | ||
import { useEffect, useRef } from 'react'; | ||
|
||
export function useOutsideClick(callback: () => void) { | ||
const ref = useRef(null); | ||
export const useOutsideClick = (callback: (event: MouseEvent) => void) => { | ||
const ref = useRef<HTMLElement | null>(null); | ||
|
||
useEffect(() => { | ||
function handleClickOutside(event: MouseEvent) { | ||
if (ref.current && !ref.current.contains(event.target)) { | ||
callback(); | ||
const handleClickOutside = (event: MouseEvent) => { | ||
if (ref.current && !ref.current.contains(event.target as Node)) { | ||
callback(event); | ||
} | ||
} | ||
}; | ||
|
||
document.addEventListener('mousedown', handleClickOutside); | ||
|
||
return () => { | ||
document.removeEventListener('mousedown', handleClickOutside); | ||
}; | ||
}, [ref, callback]); | ||
}, [callback]); | ||
|
||
return ref; | ||
} | ||
}; | ||
|
||
export default useOutsideClick; |