How to access custom attributes from event object in React?

How to access custom attributes from event object in React?

React is able to render custom attributes as described at

If you want to use a custom attribute, you should prefix it with

And that’s great news except I can’t find a way to access it from the event object e.g.:
render: function() {

removeTag: function(event) {

The element and data- property render in html fine. Standard properties like style can be accessed as fine.
Instead of I tried:[“tag”][“data-tag”][“tag”][“data-tag”]

none of these worked.


Solution 1:

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.

Related:  RequireJS: Multiple main.js?

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

Solution 2: 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:

You can do either or'data-tag'); either one works.

Solution 3:

Here’s the best way I found:

var attribute ='data-tag').value;

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

Solution 4:

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 

Solution 5:

// Method inside the component
 let tag = event.currentTarget.dataset.tag;
 console.log(tag); // should return Tagvalue
// when render element
<a data-tag="TagValue" onClick={this.userClick}>Click me</a>

Solution 6:

<div className='btn' onClick={(e) =>
    <i className='fa fa-bold' />

so e.currentTarget.attributes['tag'].value works for me

Related:  Javascript - remove an array item by value [duplicate]