HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptreactCritical

How to access custom attributes from event object in React?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
customaccessfromobjectattributesreacteventhow

Problem

React is able to render custom attributes as described at
http://facebook.github.io/react/docs/jsx-gotchas.html:


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


`

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) {
    this.setState({inputVal: event.target????}); 
},


The element and
data- property render in html fine. Standard properties like style can be accessed as event.target.style fine.
Instead of
event.target` I tried:

event.target.props.data.tag
 event.target.props.data["tag"]
 event.target.props["data-tag"]  
 event.target.data.tag
 event.target.data["tag"]
 event.target["data-tag"]


none of these worked.

Solution

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

render: function() {
    ...
    
    ...
},
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

Code Snippets

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

Context

Stack Overflow Q#20377837, score: 183

Revisions (0)

No revisions yet.