How To Get The Class Name Of An Element In React

Get the Class name of an element in React

To get the class name of an element in React you need to know what Event.target is. Through its element, you can use event. target.className to get. Let’s check the article below.

Get the class name of an element in React

Event.target is the element where the event occurred, or the event was fired. Event.currentTarget is the element that explicitly attaches the event handler. In JavaScript, we deal with and handle events by attaching handlers and event handlers to a component.

We can also wholly use event delegate assignments to avoid attaching event listeners to each component. It is also helpful in resolving and handling dynamic component events because we don’t have to attach and remove event handlers from them with event delegation.

Use event. target.className method

In this method, we will create a button Show class name, which will run a handleClick function when pressed. This function uses the event. target.className method to access the class name from the target, which is the same button tag being pressed. The example below will show you how it works.

Code:

import React from 'react';
const App = () => {
    const handleClick=(event) => {
      console.log(event.target.className);
    }
 
  return <>
    <div>
      <h2>LearnShareIT</h2>
      <p>Click the button:</p>
      <button className="button"onClick={handleClick}>Show classname</button>
    </div>
  </>;
}
export default App

Output:

button

So we can get the element’s class name, or you can refer to the method below.

Use the useRef hook method

UseRef hook is a function that returns an object with the current property initialized via the passed parameter. This returned object can be mutated and persist for the component’s lifetime.

This way, we will use the useRef hook method to set the ref for the tag we need to get the class name.

Code:

import {useEffect, useRef} from 'react';
 
export default function App() {
  const classref = useRef(null);
  useEffect(() => {
    console.log( classref.current.className);
  }, []);
  return (
    <div>
      <div ref={classref} className="learnshareit" >
        <h2>Learnshareit</h2>
      </div>
    </div>
  );
}

Output:

learnshareit

Since this is an example where we need to get the class name first, we will get it in useEffect, which runs as soon as the component mounts, and we will use ref.current.className to get the class name of the element and print it to the screen console. I hope this is helpful to you.

Summary

To summarize, there are many ways to get the class name of an element in React. After reading this article, we know some simple ways like using event. target.className method or the useRef hook method. Let’s try these methods. Good luck for you!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *