Reputation: 43
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?
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>
);
}
}
Upvotes: 4
Views: 27508
Reputation: 2081
You can do it by id
as well as data-*
attributes. But the preferred method is by data-*
attributes.
Please consider this JSFiddle link of your solution.
You should set ref on the element from which you want to extract the data and then you can use it to set data in state. IN code if you replace onClick={this.bar}
with onClick={this.barById}
then code will extract data from id
while in former case it will extract data from data-*
attributes.
Upvotes: 0
Reputation: 377
the reason why you are unable to select the id
property is that the current e.target
is the child of the <div>
, which is <p>
. Here is a proposed solution that works:
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}>
{this.state.value}
</div>
);
}
}
ReactDOM.render(<GettingAttributes />, document.querySelector("#app"))
You may also solve this by adding the click handler to the <p>
element:
<div >
<p id="foo" onClick={this.bar}>{this.state.value}</p>
</div>
Using e.currentTarget.id
will quickly solve your problem, just know what the currentTarget
stands for instead of Target
alone. Good luck!
Upvotes: 0
Reputation: 106
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.
Upvotes: 9