Using addEventListener in Function components in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
4 min

banner

# Table of Contents

  1. Using addEventListener in Function components in React
  2. Adding an event listener to the Window object in a React component
  3. Add an Event listener to the Body element in React

# Using addEventListener in Function components in React

To use the addEventListener method in function components in React:

  1. Set the ref prop on the element.
  2. Use the current property on the ref to get access to the element.
  3. Add the event listener in the useEffect hook.
App.js
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;

react add event listener to ref

The code for this article is available on GitHub

We added an event listener to an element in the useEffect hook of a component using a ref.

If you want to add an event listener to the window, or document objects, use the same approach excluding the ref.

The useRef() hook can be passed an initial value as an argument.

App.js
const ref = useRef(null);

The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the button element on which we set the ref prop.
App.js
useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; // ๐Ÿ‘‡๏ธ accessing .current property const element = ref.current; element.addEventListener('click', handleClick); return () => { element.removeEventListener('click', handleClick); }; }, []);
The code for this article is available on GitHub

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.

App.js
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 first parameter the method takes is the type of the event and the second is a function that gets invoked when an event of the specified type occurs.

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

App.js
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.

# Adding an event listener to the Window object in a React component

The same approach can be used to add an event listener to the window object.

App.js
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;

react add event listener

The code for this article is available on GitHub

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.

App.js
return () => { window.removeEventListener('click', handleClick); };

If you need to get the window's width and height, click on the following article.

# 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

The code for this article is available on GitHub

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 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.

App.js
return () => { document.body.removeEventListener('click', handleClick); };
The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev