Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.target.value is undefined for buttons that wrap an image instead of text

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?

like image 226
Tom Avatar asked Aug 25 '17 13:08

Tom


1 Answers

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.

like image 129
lukaleli Avatar answered Oct 26 '22 10:10

lukaleli