Borislav Hadzhiev
Wed Apr 27 2022·2 min read
Photo by Paz Arando
To add an event listener to the body element:
body
element on the document
object.addEventListener()
method on the body
element in the useEffect
hook.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> ); }
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.
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.
minHeight
CSS property to 100vh
to make the body element full height.I usually do this in my index.css
file.
body { min-height: 100vh; }
Make sure to import your index.css
file in your index.js
file.
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.