How To Get Data Attribute From Event Object In React

Get data attribute from Event object in React

This article will discuss how to get data attribute from Event object in React with some simple methods like the event.target.dataset.tag or event. target.getAttribute(). Let’s read this article to understand more.

Get data attribute from Event object in React

We can create our properties by adding data-* as a prefix, and you can do whatever you want.

The data attribute is also known as the data-* attribute because its syntax always appends the name of the data at the end. Data attributes should not be used to store inaccessible values if you want to hide them from users.

Use event.target.dataset method

The camelCase name or key can set and read attributes as a dataset object property: element.dataset.keyname.

So we can use the event.target.dataset method plus the data’s tag name to access and get the data we are looking for. This way, we can get all the defined data types of elements.

Code:

import React from "react";

export default function App() {
  const handleClick=(e)=>{
    console.log(e.target.dataset.number);  
  }
  return (
    <div>
      <h2>Get data attribute from Event object in React | LearnShareIT</h2>
      <button data-number="1" onClick={handleClick}>Element have data attribute</button>
    </div>
  );
}

Output:

Use event.target.getAttribute() method

The element.getAttribute() method returns the value of a particular attribute. The return value will be either null or “(an empty string)” if the given attribute is not present. There is no such thing as seeing Property for subtleties.

Syntax:

attribute =element.getAttribute(attributeName);

Parameter:

  • attributeName: Required. The name of the Property that you want to get the value of.

So we can get any attributes. Exactly here, we will get the name of the data.

Code:

import React from "react";
 
export default function App() {
  const handleClick=(e)=>{
    console.log(e.target.getAttribute("data-number"));  
  }
  return (
    <div>
      <h2>Get data attribute from Event object in React | LearnShareIT</h2>
      <button data-number="1" onClick={handleClick}>Element have data attribute</button>
    </div>
  );
}

Although the result is the same, the limitation of this approach is that you have to include the attribute with the prefix “data-” and it is pretty rigid when fixing bugs. Hope this is helpful.

Summary

To summarize, the above article has already told us how to get data attribute from Event object in React, but we recommend you use event.target.dataset method to get data neatly and more professional. Let’s try it.

Maybe you are interested:

Leave a Reply

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