Sometimes, we want to listen for click events that are outside of a component with React.
In this article, we’ll look at how to listen for click events that are outside of a component with React.
Listen for Click Events that are Outside of a Component with React
To listen for click events that are outside of a component with React, we can call window.addEventListener
to add a click event listener on the whole browser window.
For instance, we can write:
import React, { useEffect } from "react";
export default function App() {
const pageClick = (e) => {
console.log(e.target);
};
useEffect(() => {
window.addEventListener("mousedown", pageClick);
}, []);
return <div></div>;
}
to create the pageClick
function that logs e.target
, which is a property with the element that we clicked on.
Then we can use that to listen for window clicks by calling window.addEventListener
with 'mousedown'
to listen to the mousedown
event.
Now when we click anywhere in the browser window, we should see the element that we clicked on logged.
Conclusion
To listen for click events that are outside of a component with React, we can call window.addEventListener
to add a click event listener on the whole browser window.