Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Access Custom Attributes from Event Object in React

Mar 19, 2020 • 5 Minute Read

Introduction

In this guide, you will learn how to access custom attributes from an event object in React. This can be useful when you have to retrieve a custom value from a data source using a trigger, such as a button click or an option select.

Custom Attributes

Often you need to store information associated with a DOM element. This data might not be useful for displaying data to the DOM, but it is helpful for developers to access additional data. Custom attributes allow you to attach other values onto an HTML element.

Custom attributes will always start with data-. For example:

      <ul class="hotels">
  <li data-location="Integer pretium" data-id="78" class="hotel-item">
    Curabitur
  </li>
  <li data-location="Sed pharetra" data-id="122" class="hotel-item">
    Donec aliquet
  </li>
</ul>
    

Here, there are two custom data attributes: location and id. You can use these attributes to sort the hotels or search for nearby places to create an interactive experience for users.

An element can have any number of custom attributes, but it can only parse the value as a string. If you want to store an integer value, you'll have to use the parseInt() function to convert from string to integer. Note that data attribute names cannot have capital letters or special characters like "?", "&", etc.

It's best not to use data attributes for storing values that already have an appropriate attribute. For example:

      <ul data-class="hotels">
  <li data-location="Integer pretium" data-id="78" data-class="hotel-item">
    Curabitur
  </li>
  <li data-location="Sed pharetra" data-id="122" data-class="hotel-item">
    Donec aliquet
  </li>
</ul>
    

It's also best not to use attributes like data-class to store class names. It will rob you of using DOM methods for class manipulation and make it a pain to style elements.

Usage in React

Imagine that you are working on an e-commerce application, and you have a <Cart /> component. This component will be used to display the items in the user's cart.

      class Cart extends Component {
  state = { items: [] };

  async componentDidMount() {
    const items = JSON.parse(localStorage.getItem("cart"));
    this.setState({ items });
  }

  render() {
    return (
      <div className="cart">
        {this.state.items.map(item => (
          <div className="cart-item">
            <span className="item-name">{item.name}</span>
            <button>x</button>
          </div>
        ))}
      </div>
    );
  }
}
    

To remove an item when the user clicks on the x button, write a click handler function. But you still need to figure out how to identify which item to remove. So to do that, add a data-remove attribute to the button element that includes the item's id value.

      // ...
<div className="cart-item">
  <span className="item-name">{item.name}</span>
  <button onClick={this.removeItem} data-remove={item.id}>
    x
  </button>
</div>
// ...
    

Note that data-remove is a valid JSX prop name; there's no need to camel-case, like dataRemove. If you camel-case the attribute name, JSX will consider it as a prop rather than an HTML custom attribute.

Then, in the removeItem() method, access the attribute as shown below.

      // ...
removeItem = e => {
  const removeId = e.target.dataset.remove;

  // logic to remove
  const { items } = this.state;
  for (let i = items.length - 1; i >= 0; --i) {
    if (items[i].id === removeId) items.splice(i, 1);
  }
  this.setState({ items });
  localStorage.setItem("cart", JSON.stringify(items));
};
// ...
    

The target attribute of the event object will give you the native DOM node. Then you can use any DOM API to access the attributes. The dataset attribute may not be available in earlier versions of Internet Explorer. In that case, you can use the getAttribute() method.

      const removeId = e.target.getAttribute("data-remove");
    

The getAttribute() method will return the string value of the specified attribute.

Alternatively, you can also access attributes using the getNamedItem() method.

      const removeId = e.target.attributes.getNamedItem("data-remove").value;
    

Conclusion

Adding a custom attribute to an element is a great way to pass in additional data as meta properties. They can be accessed from anywhere in your application using DOM methods and objects.

That's it from this guide. I hope you learned something new today. Exploring more topics like this will help you solve and overcome common issues in coding.

Learn More

Explore these React courses from Pluralsight to continue learning:

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author