useClickAway Hook
Introduction
The useClickAway
hook is a useful custom React hook that allows you to track clicks occurring outside a specific component. It provides a way to pass a callback function that will be triggered whenever a click occurs outside the component’s area. This hook is particularly helpful when implementing dropdown menus, modals, or any other UI elements that need to be closed when the user clicks outside of them. By attaching event listeners to the document, the hook checks if the click target is within the component’s reference, and if not, it invokes the provided callback function.
Play
Usage
- Import the
useClickAway
hook into your component:
import useClickAway from "@cannonui/reacthooks";
- Initialize the hook in your component:
import { useState } from "react";
import useClickAway from "@cannonui/reacthooks";
const TestUseClickedAway = () => {
const isClickedOutside = (e: any) => {
setClickStatus(true);
};
const ref = useClickAway(isClickedOutside);
const [clickStatus, setClickStatus] = useState(false);
return (
<>
<div
ref={ref}
style={{ width: "300px", height: "200px", backgroundColor: "cyan" }}
>
Click to see if clicked outside
</div>
<div>{clickStatus ? "Clicked away" : ""}</div>
</>
);
};
export default TestUseClickedAway;
How it Works
The useClickAway
hook utilizes the useRef
and useEffect
hooks from React to handle click events outside the specified component. It returns a ref object, which should be attached to a React element to monitor click events. The ref provides a way to access the properties of the element it is attached to.
The hook sets up a click
event listener on the document and checks if the click target is outside the component’s reference. If the click occurs outside, the provided callback function is invoked.
Example
In the example above, we have created a simple component TestUseClickedAway
that uses the useClickAway
hook to track whether a click occurs outside the <div>
element with the cyan background. If a click happens outside the <div>
, it sets the clickStatus
state to true
, indicating that the user has clicked away.
This custom hook can be helpful when you need to implement UI elements that should be closed when users interact outside of them.
Please note that this hook tracks click events only on the client-side and may not be accurate during server-side rendering or when running on the server.