Reputation: 12230
I'm rendering list of years (2017,2018,2019 ..etc)
I'm trying to console.log year value
<a href="#" onClick={() => console.log(event.target.getAttribute('data-year'))} data-year={year}>{year}</a>
I have tried getAttribute but keep getting 'undefined'
event.target.getAttribute('data-year')
https://jsfiddle.net/69z2wepo/83227/
Any ideas?
Upvotes: 1
Views: 757
Reputation: 74176
Try using a data attribute and event.target.dataset.value
:
class ControlText extends React.Component {
constructor(props){
super(props);
this.state = {
value: ""
};
}
update(event) {
console.log(event);
this.setState({value: event.target.dataset.value});
}
render() {
console.log(this.state);
var value = this.state.value;
return <a type="text" data-value={2017} onClick={this.update.bind(this)} > 2017 </a>
}
}
ReactDOM.render(
<ControlText />,
document.getElementById('container')
);
Working example: https://jsfiddle.net/rejee84L/
Upvotes: 1
Reputation: 301
Your code as posted appears to have a typo--your console.log doesn't having a closing parenthesis. In addition, you don't really need to use event.target.value here. Check it out:
<a href="#" onClick={ () => console.log(year) }>{year}</a>
When React creates the <a>
element it knows what your year variable is and can use it in the console.log function.
Upvotes: 0