How to access custom attributes from event object in React?

Here's the best way I found:

var attribute = event.target.attributes.getNamedItem('data-tag').value;

Those attributes are stored in a "NamedNodeMap", which you can access easily with the getNamedItem method.


To help you get the desired outcome in perhaps a different way than you asked:

render: function() {
    ...
    <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
    ...
},
removeTag: function(i) {
    // do whatever
},

Notice the bind(). Because this is all javascript, you can do handy things like that. We no longer need to attach data to DOM nodes in order to keep track of them.

IMO this is much cleaner than relying on DOM events.

Update April 2017: These days I would write onClick={() => this.removeTag(i)} instead of .bind


event.target gives you the native DOM node, then you need to use the regular DOM APIs to access attributes. Here are docs on how to do that:Using data attributes.

You can do either event.target.dataset.tag or event.target.getAttribute('data-tag'); either one works.


Or you can use a closure :

render: function() {
...
<a data-tag={i} style={showStyle} onClick={this.removeTag(i)}></a>
...
},
removeTag: function (i) {
    return function (e) {
    // and you get both `i` and the event `e`
    }.bind(this) //important to bind function 
}