Check if an Element contains a class in React

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

Check if an Element contains a class in React #

To check if an element contains a class in React:

  1. Set the ref prop on the element.
  2. Use the classList.contains() method on the ref object to check if the class exists.
  3. The method returns true if the element's class list contains the class.
App.js
import {useEffect, useRef} from 'react'; export default function App() { const ref = useRef(null); // 👇️ check if element contains class on mount useEffect(() => { if (ref.current.classList.contains('my-class')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); } }, []); // 👇️ check if element contains class on click const handleClick = event => { if (event.currentTarget.classList.contains('my-class')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); } }; return ( <div> <div ref={ref} className="my-class" onClick={handleClick}> Hello world </div> </div> ); }

check if element has class

The code snippet shows how to check if an element contains a class when the component is mounted or when the element is clicked.

The useRef() hook can be passed an initial value as an argument. 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 div element on which we set the ref prop.

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.

The classList.contains method returns a boolean value - true if the class is contained in the element's class list and false otherwise.

If you need to check if an element contains a class on click, set the onClick prop on the element.

The handleClick function gets invoked every time the element is clicked.

Notice that we used the currentTarget property on the event because we want to access the element that the event listener is attached to.

The target property on the event gives us a reference to the element that triggered the event (could be a descendant).

In our handleClick method, we again use the classList.contains() method to check if the element contains the class.

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.