13

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:

target_value

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?

arshovon
  • 13,270
  • 9
  • 51
  • 69

1 Answers1

21

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:

  1. Target value sometimes undefined
  2. event target vs event currenttarget
  3. MDN Event.currentTarget
Nagev
  • 10,835
  • 4
  • 58
  • 69
arshovon
  • 13,270
  • 9
  • 51
  • 69
  • Very nice the example, thank you. Here some more references that could help someone else: https://stackoverflow.com/questions/10086427/what-is-the-exact-difference-between-currenttarget-property-and-target-property I think you could add your example to this other thread, it would probably help a lot of people. – Guilherme Abacherli Apr 20 '22 at 00:04