Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'target' of undefined

In my render method I have component

<DatePicker selected={this.state.startDate} onChange={this.handleChange()}/>

handleChange is following

handleChange: function (e) {
  var that = this;
  console.log(e.target.value)
  return function () {
    that.setState({
      startDate: e.target.value
    });
  }
},

By when I try to load page with this component, I get error

Cannot read property 'target' of undefined

What am I doing wrong ?

like image 303
Alexey K Avatar asked Sep 24 '17 10:09

Alexey K


2 Answers

The problem is that you are invoking the function in this line:

onChange={this.handleChange()}

All you have to do is simply pass the function as a value to onChange without invoking it.

onChange={this.handleChange}

When you use parenthesis you'd be invoking a function/method instead of binding it with an event handler. Compare the following two examples:

//invokes handleChange() and stores what the function returns in testA.
const testA = this.handleChange()  

vs

//stores the function itself in testB. testB be is now a function and may be invoked - testB();
const testB = this.handleChange 
like image 70
Matthew Barbara Avatar answered Oct 17 '22 09:10

Matthew Barbara


If you are passing event using an arrow function, you should try the following:

onChange={(e) => handleChange(e)}
like image 41
Andreas Bigger Avatar answered Oct 17 '22 07:10

Andreas Bigger