Borislav Hadzhiev
Wed Apr 27 2022·2 min read
Photo by Riley
To get the class name of an element in React:
ref
prop on the element or use an event handler function.ref.current.className
.event.currentTarget.className
.import {useEffect, useRef} from 'react'; export default function App() { const ref = useRef(null); useEffect(() => { console.log('className 👉️', ref.current.className); // 👇️ check if element contains class if (ref.current.classList.contains('my-class')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); } }, []); const handleClick = event => { console.log('className 👉️', event.currentTarget.className); // 👇️ check if element contains class 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> ); }
The code snippet shows how to get the class name of an element when the component mounts, or when an event is triggered.
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.
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.
useEffect(() => { console.log('className 👉️', ref.current.className); // 👇️ check if element contains class if (ref.current.classList.contains('my-class')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); } }, []);
We used the className property to programmatically get the element's class name.
If you need to get the element's class name when an event is triggered, use
event.currentTarget.className
.
We set the onClick
prop on the div
element, so every time it is clicked, its
handleClick
function is invoked.
const handleClick = event => { console.log('className 👉️', event.currentTarget.className); // 👇️ check if element contains class if (event.currentTarget.classList.contains('my-class')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); } };
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).
This means that if you need to access the class name of the element that was
actually clicked, not the one to which the event listener is attached, you would
use the target
property instead.
const handleClick = event => { console.log('className 👉️', event.target.className); };