Author avatar

Gaurav Singhal

How to Access Custom Attributes from Event Object in React

Gaurav Singhal

  • Mar 19, 2020
  • 5 Min read
  • 4,240 Views
  • Mar 19, 2020
  • 5 Min read
  • 4,240 Views
Web Development
Front End Web Development
Client-side Framework
React

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:

1
2
3
4
5
6
7
8
<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>
html

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:

1
2
3
4
5
6
7
8
<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>
html

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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>
    );
  }
}
jsx

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.

1
2
3
4
5
6
7
8
// ...
<div className="cart-item">
  <span className="item-name">{item.name}</span>
  <button onClick={this.removeItem} data-remove={item.id}>
    x
  </button>
</div>
// ...
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
// ...
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));
};
// ...
jsx

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.

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

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

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

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

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.

8