So I'm trying to retrieve data in a div attribute in react. JSFiddle shows the problems I'm having. this.state.value is set to an empty string after the event fires.
I started off using the data-* attribute for the div after reading another stack overflow post, but I cannot use jQuery, so I switched to id. Any ideas?
JSFiddle
class GettingAttributes extends React.Component {
constructor(props) {
super(props)
this.state = {value: 'Hello!'};
this.bar = this.bar.bind(this);
}
bar(e){
this.setState({value: e.target.id})
}
render() {
return (
<div id="foo" onClick={this.bar}>
<p>{this.state.value}</p>
</div>
);
}
}
Use
e.currentTarget.id
instead of
e.target.id
.currentTarget will target the element that actually contains the event listener. In your scenario, .target is the p tag with the text in it, which doesn't have an id to set in your state.
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