I was catching an input value in event handler like below:
import React from 'react';
export class Newsletter extends React.Component {
handleClick(event) {
let newsletterId = event.target.value;
console.log(newsletterId);
}
constructor(props) {
super(props);
this.state = {
newsletter: this.props.newsletter,
}
}
render() {
return (
<div className="col-sm-4 col-xs-12">
<button onClick={this.handleClick.bind(this)}
value={this.state.newsletter.pk}>
<span className="fa fa-arrow-right"></span>
</button>
</div>
)
}
}
This was behaving strangely. Target value sometimes become undefined
. Sometimes I was getting the correct newsletterId
and sometimes I was getting undefined
. See the screenshot below:
Then I changed event.target.value
to event.currentTarget.value
. Now it is working smoothly.
So, the question arose, What's the difference between event.target.value
and event.currentTarget.value
in this scenario?
What was the cause of this strange behavior? Why I was getting the expected value sometimes?
This was happening because I was clicking on the span
element which is inside the button
element. While clicking on the button
sometimes I was actually clicking on the span
element. Those clicks are not bound to the button
element rather it fires the click event on span
element. And that was the reason of this strange behavior.
In short,
target
: whatever element somebody actually clicked on. It can vary, as this can be within an element that the event was bound to.
currentTarget
: is the element you actually bound the event to. This will never change.
Reference:
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