Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access data attributes from event object

Tags:

reactjs

jsfiddle

var Hello = React.createClass({   handleClick(event){     console.log('target info', event.currentTarget);     console.log('event info', event);     var sortOrder = event.currentTarget.sortorder;      console.log('sortOrder: ', sortOrder);     alert(sortOrder);//Should say "asc"   },   render: function() {     return <div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" onClick={this.handleClick}>Click Here Please</div>;   } });  ReactDOM.render(   <Hello name="World" />,   document.getElementById('container') ); 

Expected Output: asc
Actual: undefined

like image 934
P.Brian.Mackey Avatar asked Jun 20 '16 18:06

P.Brian.Mackey


People also ask

How do you target attributes in React?

To set the target prop of an element to _blank in React, use an anchor element and set the rel prop, e.g. <a href="https://example.com" target="_blank" rel="noopener noreferrer"> . The _blank value means that the resource is loaded into a new tab. Copied!

How do you use data attribute in React?

To set a data attribute on an element in React, set the attribute directly on the element, e.g. <button data-test-id="my-btn"> or use the setAttribute() method, e.g. el. setAttribute('data-foo', 'bar') . You can access the element on the event object or using a ref . Copied!


1 Answers

I updated your fiddle:

I was able to do it just by referencing with "getAttribute"

 event.target.getAttribute("data-sortorder"); 

this is with refs https://jsfiddle.net/69z2wepo/46265/

 var sortOrder = this.refs.tester.getAttribute("data-sortorder");  alert(sortOrder);//Should say "asc" },   render: function() {     return <div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" ref="tester" onClick={this.handleClick}>Click Here Please</div>;   } }); 

Do this:-

  1. change your element, by adding a "ref" attribute.

    div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" ref="tester" onClick={this.handleClick} 
  2. Then get that attribute like so: this.refs.tester.getAttribute("data-sortorder")

OR PER ORIGINAL REQUEST, w/o REFS:

  1. Or per "event specific" -- it worked properly referencing it like so: event.target.getAttribute("data-sortorder");
like image 120
james emanon Avatar answered Sep 18 '22 06:09

james emanon