Created
August 3, 2025 15:19
-
-
Save roykho/738d7745e562cf14558ee44f9eb69282 to your computer and use it in GitHub Desktop.
React - Handy click outside container handler
This file contains hidden or 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, useRef } from 'react'; | |
| const useClickOutside = (callback: () => void) => { | |
| const ref = useRef<HTMLElement>(null); | |
| useEffect(() => { | |
| const handleClickOutside = (event: MouseEvent) => { | |
| // If the ref exists and the clicked element is not inside the ref's element | |
| if (ref.current && !ref.current.contains(event.target as Node)) { | |
| callback(); // Execute the provided callback function | |
| } | |
| }; | |
| const handleKeyDown = (event: KeyboardEvent) => { | |
| // Check if the escape key was pressed | |
| if (event.key === 'Escape') { | |
| callback(); // Execute the provided callback function | |
| } | |
| }; | |
| // Add event listeners to the document | |
| document.addEventListener('mousedown', handleClickOutside); | |
| document.addEventListener('keydown', handleKeyDown); | |
| // Clean up the event listeners when the component unmounts or dependencies change | |
| return () => { | |
| document.removeEventListener('mousedown', handleClickOutside); | |
| document.removeEventListener('keydown', handleKeyDown); | |
| }; | |
| }, [callback]); // Re-run effect if the callback function changes | |
| return ref; // Return the ref to be attached to the target element | |
| }; | |
| export default useClickOutside; | |
| // USAGE: | |
| Add a ref to the container you're targeting. | |
| const component = () => { | |
| const containerRef = useClickOutside(() => setShowContainer(false)); | |
| return ( | |
| <div ref={containerRef}>Hello</div> | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment