How to Access Custom Attributes from an Event Object in React?

Sometimes, we want to access custom attributes from an event object in React.

In this article, we’ll look at how to access custom attributes from an event object in React.

Access Custom Attributes from an Event Object in React

To access custom attributes from an event object in React, we can use the e.currentTarget.dataset property.

For instance, we write:

import React from "react";

export default function App() {
  const onClick = (e) => {
    const tag = e.currentTarget.dataset.tag;
    console.log(tag);
  };

  return (
    <button data-tag="Tag Value" onClick={onClick}>
      Click me
    </button>
  );
}

We have the e.currentTarget.dataset.tag property to access the value of the data-tag attribute of the element we clicked on in the onClick function.

Then we assign the onClick function as the value of the onClick prop of the button.

And we set the data-tag attribute to Tag Value.

Now when we click on the button, we should see the data-tag attribute value logged in the console.

Conclusion

To access custom attributes from an event object in React, we can use the e.currentTarget.dataset property.