Add an Event listener to the Body element in React

avatar

Borislav Hadzhiev

Last updated: Apr 27, 2022

banner

Photo from Unsplash

Add an Event listener to the Body element in React #

To add an event listener to the body element:

  1. Access the body element on the document object.
  2. Use the addEventListener() method on the body element in the useEffect hook.
  3. Remove the event listener when the component unmounts.
App.js
import {useEffect} from 'react'; export default function App() { useEffect(() => { function handleClick() { console.log('click event triggered'); } // 👇️ optionally set body height to full screen document.body.style.minHeight = '100vh'; document.body.addEventListener('click', handleClick); return () => { // 👇️ remove event listener when the component unmounts document.body.removeEventListener('click', handleClick); }; }, []); return ( <div> <h2>Hello world</h2> </div> ); }

add event listener to body element

We can access the body element on the document object.

We passed an empty dependencies array to the useEffect hook because we only want to add the event listener to the body element once - when the component mounts.

App.js
useEffect(() => { function handleClick() { console.log('click event triggered'); } document.body.style.minHeight = '100vh'; document.body.addEventListener('click', handleClick); return () => { document.body.removeEventListener('click', handleClick); }; }, []);

The example shows how to add a click event listener, but this approach would work for any other event type.

The first parameter the addEventListener method takes is the type of the event to listen for, and the second is a function that gets invoked when an event of the specified type occurs.

In the example, we set the minHeight CSS property to 100vh to make the body element full height.

I usually do this in my index.css file.

index.css
body { min-height: 100vh; }

Make sure to import your index.css file in your index.js file.

index.js
import './index.css'

The function we returned from the useEffect hook is called when the component unmounts.

We used the removeEventListener method to remove the event listener that we previously registered.

The cleanup step is important, because we want to make sure we don't have any memory leaks in our application.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.