Last active
February 10, 2023 06:18
-
-
Save Hat52/4dbcee07f34c96153a68b4327bea4157 to your computer and use it in GitHub Desktop.
React Hook for Detecting Clicks Outside a Component: This is a simple and efficient way to detect clicks outside a React component. By using the MutableRefObject and useEffect hooks from React, you can easily listen to mousedown events on the document and trigger a callback function when a click outside of a component is detected. This is useful…
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 { MutableRefObject, useEffect,useState } from 'react'; | |
// Define the type for the hook, which takes two arguments: a reference to a component and a callback function | |
type OutsideNotifierHook = ( | |
ref: MutableRefObject<any>, // The reference to the component | |
onOutsideClick: (isInside: false) => void // The callback function that will be triggered when a click outside of the component is detected | |
) => void; | |
// The implementation of the hook, which will be exported for use in other components | |
const useOutsideClick: OutsideNotifierHook = (ref, onOutsideClick) => { | |
useEffect(() => { | |
// Define a handleClick function that will be passed as an event listener to the document | |
const handleClick = (e: MouseEvent) => { | |
// Check if the click occurred inside or outside of the component | |
if (ref.current && !ref.current.contains(e.target)) { | |
// Trigger the "onOutsideClick" callback function if the click was outside of the | |
onOutsideClick(false); | |
} | |
}; | |
// Add the handleClick function as an event listener for "mousedown" events on the document | |
document.addEventListener('mousedown', handleClick); | |
// Return a cleanup function that will remove the event listener when the component is unmounted | |
return () => document.removeEventListener('mousedown', handleClick); | |
}, [ref, onOutsideClick]); | |
}; | |
export default useOutsideClick | |
; | |
//Usage example | |
const Example = () =>{ | |
const [visible,setVisible] = useState(false) | |
const ref = useRef<any>(null) | |
useOutSideClick(ref,setVisible) | |
return ( | |
<div> | |
<p>{visible?'Visible':'Invisible'} | |
{ | |
visible? | |
<ul ref={ref} > | |
<li>Option 1</li> | |
<li>Option 2</li> | |
<li>Option 3</li> | |
<li>Option 4</li> | |
</ul> | |
:null} | |
</div> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment