Reputation: 2832
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
Reputation: 3048
It's difficult to know for sure without looking at your program as a whole, but here's what's possibly happening:
props.onClickHandler
is evaluated at the time the button is clicked.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