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
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!
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!
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:-
change your element, by adding a "ref" attribute.
div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" ref="tester" onClick={this.handleClick}
Then get that attribute like so: this.refs.tester.getAttribute("data-sortorder")
OR PER ORIGINAL REQUEST, w/o REFS:
event.target.getAttribute("data-sortorder");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With