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.
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<ul class="hotels">
2 <li data-location="Integer pretium" data-id="78" class="hotel-item">
3 Curabitur
4 </li>
5 <li data-location="Sed pharetra" data-id="122" class="hotel-item">
6 Donec aliquet
7 </li>
8</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:
1<ul data-class="hotels">
2 <li data-location="Integer pretium" data-id="78" data-class="hotel-item">
3 Curabitur
4 </li>
5 <li data-location="Sed pharetra" data-id="122" data-class="hotel-item">
6 Donec aliquet
7 </li>
8</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.
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.
1class Cart extends Component {
2 state = { items: [] };
3
4 async componentDidMount() {
5 const items = JSON.parse(localStorage.getItem("cart"));
6 this.setState({ items });
7 }
8
9 render() {
10 return (
11 <div className="cart">
12 {this.state.items.map(item => (
13 <div className="cart-item">
14 <span className="item-name">{item.name}</span>
15 <button>x</button>
16 </div>
17 ))}
18 </div>
19 );
20 }
21}
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<div className="cart-item">
3 <span className="item-name">{item.name}</span>
4 <button onClick={this.removeItem} data-remove={item.id}>
5 x
6 </button>
7</div>
8// ...
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// ...
2removeItem = e => {
3 const removeId = e.target.dataset.remove;
4
5 // logic to remove
6 const { items } = this.state;
7 for (let i = items.length - 1; i >= 0; --i) {
8 if (items[i].id === removeId) items.splice(i, 1);
9 }
10 this.setState({ items });
11 localStorage.setItem("cart", JSON.stringify(items));
12};
13// ...
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.
1const 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.
1const removeId = e.target.attributes.getNamedItem("data-remove").value;
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.
Explore these React courses from Pluralsight to continue learning: