I have two buttons that are identical, except one has an image inside it and the other has text. I have added an onClick event handler to both.
The event.target.value for the image button is undefined, despite having a value and the text button has the correct value.
See this fiddle for an example: https://jsfiddle.net/69z2wepo/84885/
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.changeSlide = this.changeSlide.bind(this);
}
changeSlide(e) {
e.preventDefault();
console.log('e.target.value', e.target.value);
}
render() {
return (
<div>
<button
onClick={this.changeSlide}
value="back">
<img src="//www.gravatar.com/avatar/7150a453468d14f599772cd8330fcf25/?default=&s=80" alt="Previous slide" />
</button>
<button
onClick={this.changeSlide}
value="back">
CLICK ME
</button>
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('container')
);
Why is this the case and what is the correct way to use images inside buttons?
You need to change target
to currentTarget
:
changeSlide(e) {
e.preventDefault()
console.log(e.currentTarget.value)
}
From the DOM Event documentation:
Event.currentTarget Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.
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