Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between event.target.value and event.currentTarget.value

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?

like image 686
arsho Avatar asked Dec 28 '17 05:12

arsho


1 Answers

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
like image 173
arsho Avatar answered Oct 12 '22 15:10

arsho