As a developer, you might have come across situations where you need to detect when a user clicks outside of a particular element in your NextJs or React app. For example, you might have a dropdown menu that you want to close when a user clicks outside of it or a modal. In this post, we'll explore how to detect clicks outside of an element in NextJS or React using the useRef and useEffect hooks.
To get started, let's take a look at the following code snippet:
import { useEffect, useRef } from "react";
const Component = () => {
const ref = useRef(null);
useEffect(() => {
const handleOutSideClick = (event) => {
if (!ref.current?.contains(event.target)) {
alert("Outside Clicked.");
console.log("Outside Clicked. ");
}
};
window.addEventListener("mousedown", handleOutSideClick);
return () => {
window.removeEventListener("mousedown", handleOutSideClick);
};
}, [ref]);
return (
<div className="w-screen h-screen bg-yellow-200 flex justify-center items-center">
<div className="w-96 h-96 bg-orange-500" ref={ref}>
Click outside of me.
</div>
</div>
);
};
export default Component;
In this code snippet, we have a functional component called Component
. The component renders a div
element that has a child div
element with the text "Click outside of me". We use the useRef
hook to create a ref that we can use to reference the child div
element.
The useEffect
hook is used to add an event listener to the window
object for the "mousedown" event. When the event is triggered, the handleOutSideClick
function is called. This function checks if the event.target
(i.e., the element that was clicked) is inside the child div
element. If the clicked element is not inside the child div
element, it means that the user clicked outside of the child div
element. In this case, we alert the user that the outside was clicked and log the message "Outside Clicked" to the console.
We also return a function from the useEffect
hook that removes the event listener when the component is unmounted. This is to avoid memory leaks.
To test this code, you can run the NextJS or React app and click anywhere on the screen outside of the child div
element. You should see an alert with the message "Outside Clicked" and the message should be logged to the console.
In conclusion, detecting clicks outside of an element in NextJS or React can be achieved using the useRef
and useEffect
hooks. By creating a ref to reference the child element and adding an event listener to the window
object, we can detect clicks outside of the element and perform the desired action.
Top comments (3)
Awesome, it was helpful, thanks man.
Great article. Thanks for writing this things in a simple way.
Very concise and straight forward blog thank Teacher.