Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access custom attributes from event object in React?

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-.

<div data-custom-attribute="foo" />

And that's great news except I can't find a way to access it from the event object e.g.:

render: function() { ... <a data-tag={i} style={showStyle} onClick={this.removeTag}></a> ... 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.

like image 568
andriy_sof Avatar asked Dec 04 '13 14:12

andriy_sof


People also ask

How do you get data attribute from event React?

Use the target. dataset property to access data attributes from the event object in React. The dataset property provides read and write access to the custom data attributes of the element.

How do I get tag value in React?

When the button element is clicked, the click event gets triggered, the value of the tagName property can be used to find out HTML element the source of the event and innerText property can be used to find out text written in that HTML element.


2 Answers

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.

like image 88
Sophie Alpert Avatar answered Sep 30 '22 10:09

Sophie Alpert


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

like image 29
Jared Forsyth Avatar answered Sep 30 '22 10:09

Jared Forsyth