Last updated: Apr 7, 2024
Reading timeยท4 min
To use the addEventListener
method in function components in React:
ref
prop on the element.current
property on the ref to get access to the element.useEffect
hook.import {useRef, useEffect} from 'react'; const App = () => { const ref = useRef(null); useEffect(() => { const handleClick = event => { console.log('Button clicked'); console.log('bobbyhadz.com'); }; const element = ref.current; element.addEventListener('click', handleClick); return () => { element.removeEventListener('click', handleClick); }; }, []); return ( <div> <button ref={ref}>Click</button> </div> ); }; export default App;
We added an event listener to an element in the useEffect
hook of a component
using a ref
.
window
, or document
objects, use the same approach excluding the ref
.The useRef() hook can be passed an initial value as an argument.
const ref = useRef(null);
The hook returns a mutable ref object whose .current
property is initialized
to the passed argument.
current
property on the ref object to get access to the button
element on which we set the ref
prop.useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; // ๐๏ธ accessing .current property const element = ref.current; element.addEventListener('click', handleClick); return () => { element.removeEventListener('click', handleClick); }; }, []);
When we pass a ref prop to an element, e.g. <div ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
We passed an empty dependencies array to the useEffect hook, so it's only going to run when the component mounts.
We only want to call the addEventListener
method once - when the component
mounts.
useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; const element = ref.current; element.addEventListener('click', handleClick); return () => { element.removeEventListener('click', handleClick); }; }, []);
We stored a reference to the element in a variable and used the
addEventListener
method to add a click
event listener to the button.
The function we returned from the useEffect
hook is called when the component
unmounts.
return () => { element.removeEventListener('click', handleClick); };
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.
The same approach can be used to add an event listener to the window
object.
import {useEffect} from 'react'; const App = () => { useEffect(() => { const handleClick = event => { console.log('Window clicked'); console.log('--------------'); }; window.addEventListener('click', handleClick); return () => { window.removeEventListener('click', handleClick); }; }, []); return ( <div> <h2>bobbyhadz.com</h2> </div> ); }; export default App;
When adding an event listener to the window
object, we don't have to use a
ref
.
Every time the user clicks on the window, the handleClick
function is invoked.
When the component unmounts, the cleanup function runs and removes the event listener.
return () => { window.removeEventListener('click', handleClick); };
If you need to get the window's width and height, click on the following article.
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 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.
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.
return () => { document.body.removeEventListener('click', handleClick); };
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.
The same approach can be used to add a class or styles to the body element.
If you need to add or remove a class on click, check out the following tutorial.
You can learn more about the related topics by checking out the following tutorials: