Chandrahas Balleda
Chandrahas Balleda

Reputation: 2832

TypeError: Cannot read property 'bind' of undefined - ReactJS

I am getting the below error while binding the values to the function.

TypeError: Cannot read property 'bind' of undefined

Please see the code below:

<button className={classes.ButtonStyle} onClick={props.onClickHandler.bind(null,props.id)}>{props.children}</button>

But the arrow function notation is working fine though:

onClick={(e)=>{props.onClickHandler(props.id,e)}}

May I please know where I have done wrong? Also I am not using class based components but only functional based components(hooks).

The onClickHandler function is as below:

const onClickHandler = (id, e) =>{
    e.preventDefault();
    console.log('buttonSetNullHandler', id);
}

Upvotes: 0

Views: 151

Answers (1)

Jono Job
Jono Job

Reputation: 3048

It's difficult to know for sure without looking at your program as a whole, but here's what's possibly happening:

  • With the arrow function style, props.onClickHandler is evaluated at the time the button is clicked.
  • With the bind style, the bind will be executed when the component first mounts.

My guess is that when the component first mounts, props.onClickHandler is not set, but it is being set in a subsequent render that happens before you click the button.

It should be easy to check by putting a console.log(props) in the render function and seeing how many times it happens and what the props are each time.


As an aside, I personally would go with the arrow style over the bind style - onClick={e => props.onClickHandler(props.id,e)} is likely to be much less surprising to the developer coming after you. :)

Upvotes: 1

Related Questions