0

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);
}
6
  • if you are using functional component, then why are you using bind here, ?? onClick={()=> props.onClickHandler(props.id) } this should definitely do the job. why over cooking Commented Aug 7, 2019 at 5:59
  • I got your point, but bind works in functional components too right. I just don't want to explicitly send event - e. So, using bind Commented Aug 7, 2019 at 6:01
  • @meral head, I dont know in dept, you can refer the documentation here, reactjs.org/docs/handling-events.html Commented Aug 7, 2019 at 6:07
  • Another small error is that you defined the id as the first parameter the second one the event. When you are using it, you set the first argument as null and the second one as id. Commented Aug 7, 2019 at 6:10
  • But while binding since we need to pass object as first parameter, hence made it null and second parameter is the value to be passed. Since event is automatically passed as last parameter hence didn't specify it explicitly. Please correct me if I am wrong. Thank you Commented Aug 7, 2019 at 6:45

1 Answer 1

1

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. :)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.