Categories
React Answers

How to Add a Click Handler to the Body Element from within a React Component?

Spread the love

Sometimes, we want to add a click handler to the body element from within a React component.

In this article, we’ll look at how to add a click handler to the body element from within a React component.

Add a Click Handler to the Body Element from within a React Component

To add a click handler to the body element from within a React component, we call the addEventListener method on document.body in the useEffect hook callback to starting listening to clicks on the body element when the component loads.

For instance, we can write:

import React, { useEffect } from "react";
export default function App() {
  useEffect(() => {
    const onClick = () => {
      console.log("body clicked");
    };
    document.body.addEventListener("click", onClick);

    return () => {
      document.body.removeEventListener("click", onClick);
    };
  }, []);

  return <div>hello world</div>;
}

to call the useEffect hook with a callback that calls document.body.addEventListener with 'click' and onClick to add the onClick function as the event listener for click events emitted from the body element.

Also, we return function that calls removeListener to remove the body click listener when the component is unmounted.

And we pass in an empty array as the 2nd argument of useEffect to run the useEffect callback only when the component mounts.

Now when we click on the body element, we should see 'body clicked' logged in the console.

Conclusion

To add a click handler to the body element from within a React component, we call the addEventListener method on document.body in the useEffect hook callback to starting listening to clicks on the body element when the component loads.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *