Reputation: 90
How to get the value of a clicked element in react. event.currentTarget.value shows 'undefined' in react 16. Does anyone know what is the trick here ?? BTM here is the code for an instance:
class Test extends React.Component{
constructor(){
super();
}
changeDimension(e){
alert(e.currentTarget.value);
}
render(){
return(
<div style={{height : this.state.height}} >
<h1 onClick={this.changeDimension.bind(this)}> Click Me</h1>
</div>
);
}
}
Upvotes: 1
Views: 4497
Reputation: 11
If you want something other than "Click Me" alerted:
<h1 onClick={this.changeDimension.bind(this)} data-value="something other"> Click Me</h1>
Then:
alert(event.target.dataset.value)
Upvotes: 1
Reputation: 1743
on those cases , i generally pass directly the value as a parameter on the function , especially if i have multiple buttons generated by a loop , for example :
{this.state.dimensions.map(dimension => <h1 onClick={() => this.changeDimension(dimension)}>{dimension.value}</h1>)}
Upvotes: 0
Reputation: 5542
The value
attribute is not set in:
<h1 onClick={this.changeDimension.bind(this)}> Click Me</h1>
If you need the "Click Me" text then use:
alert(e.currentTarget.innerHTML);
Upvotes: 3