How to access custom attributes from event object in React?
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
How to access data attributes from event object
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:
- Or per "event specific" -- it worked properly referencing it like so:
event.target.getAttribute("data-sortorder");
NOTE: Now that we are 6yrs later, you can also use: (per niko9911 suggestion below)
event.target.dataset.sortorder
--> You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase).
How to access custom attribute value of option in react
onChange()
event handler has access to selected options elements (single for regular <select>
) through event.target.selectedOptions
In order to get data-set
attribute you may leverage data-*
API. In a nutshell, it provides access to data-*
attributes through .dataset
property of HTMLElement (hence, data-set value is accessible via .dataset.set):
So, with a bit of destructuring, your task may be solved as easy as that:
const { render } = ReactDOM
const Select = () => {
const onChangeSelectedOption = ({
target: {
selectedOptions: [{
dataset: {set}
}]
}
}) => console.log(set)
return (
<select onChange={onChangeSelectedOption}>
<option selected disabled>Select...</option>
<option value="1" data-set="demo1">Value 1</option>
<option value="2" data-set="demo2">Value 2</option>
<option value="3" data-set="demo3">Value 3</option>
</select>
)
}
render (
<Select />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
Retrieve custom data-* attributes value in React Component(without event)
Something like this?
var blogs = document.querySelectorAll('.blog');
for(var i = 0; i < blogs.length; i++){
createComponent(blogs[i]);
}
function createComponent(blog){
ReactDOM.render(<Blog blogtitle={blog.dataset.title} />, blog)
}
Fiddle: https://jsfiddle.net/rtLux0f6/1/
React get data attributes on html tag in onChange handler
I've noticed that you have missed an opening curly brace in your setState
call. And that will throw a syntax error when you run it. It should be fixed like this:
handleInputChange = (event) => {
this.setState({[event.target.inputName]: event.target.value})
}
For accessing your data attribute from the handleInputChange
, you can do it like this:
handleInputChange = event => {
this.setState({
[event.target.getAttribute('data-input-name')]: event.target.value,
});
};
And also, you can use the default name attributes that comes with these inputs like this:
handleInputChange = event => {
this.setState({
[event.target.name]: event.target.value,
});
};
// in your render fucntion
<input
onChange={this.handleInputChange}
type="text"
name="name"
value={this.state.name}
/>
This will work as the same as using data attributes. Hope this help!
Related Topics
Angularjs - How to Get an Ngrepeat Filtered Result Reference
Difference Between "Process.Stdout.Write" and "Console.Log" in Node.Js
Detect When a Window Is Resized Using JavaScript
How to Skip Over an Element in .Map()
Wrapping Lines/Polygons Across the Antimeridian in Leaflet.Js
How to Use Redis Publish/Subscribe with Nodejs to Notify Clients When Data Values Change
Property 'Value' Does Not Exist on Type Eventtarget in Typescript
Get Path Params in React-Router V4
JavaScript Getelementbyid Based on a Partial String
How to Get Index in Handlebars Each Helper
How to Sort/Order Keys in JavaScript Objects
Is Performing a Mapping Operation Without Using Returned Value an Antipattern
Javascript: Call a Function After Specific Time Period
Replace All Spaces in a String with '+'
How to Access Google Sheet Spreadsheets Only with JavaScript
How to Configure Different Environments in Angular.Js