0

I got undefined value passing e using arrow function

<input type="checkbox" onChange={e=> this.handleCheck(this, 123)} />

handleCheck = (e, number) => {
console.log(number) //123
console.log(e.target.checked) //undefined
console.log(e.target) //undefined
}

What's wrong?

pvg
  • 2,673
  • 4
  • 17
  • 31
Alan Jenshen
  • 3,159
  • 9
  • 22
  • 35

1 Answers1

0

In your code e.target will be undefined. It is because you are passing this as argument and this is reference to Reactclass`.

case 1.

 <input type="checkbox"  onChange={e=> this.handleCheck(e, 123)}/>


Here `e` is value  not event. console.log(e) will print true on checked and false on unchecked.

Case 2:

 <input type="checkbox" onChange={this.handleCheck.bind(this)}/>//this is event here

    handleCheck(e)
    {
     console.log(e.target.value)// Here you will get value
    }

case 3:

 <input type="checkbox" value="me" onChange={this.handleCheck.bind(this,123)}/>//this is event here

    handleCheck(value,e)// if you bind method to this and pass extra arguments than you will get it in reverse order
    {
console.log(value)//123
     console.log(e.target.value)// me
    }
Ved
  • 11,837
  • 5
  • 42
  • 60