0

I've got an onClick props in a React component that contains the following:

onClick={_.bind(this.callMe, this, argToPass)}

Keep in mind, this is in a React component that uses React.createClass, so the component functions should be bound to it's context.

Unfortunately, when I attempt to bind this by doing the following:

onClick={this.callMe(argToPass)}

It breaks one of my tests.

I don't want to bind it as it's passed as props like this:

onClick={this.callMe(argToPass).bind(this)}

b/c of performance issues.

What is the vanilla javascript equivalent of:

_.bind(this.callMe, this, argToPass)

That will allow the function to bind correctly.

Thanks!

zero_cool
  • 3,960
  • 5
  • 39
  • 54
  • Dude. Who downvotes without an explanation? This is legit, in production on a fantastic team, and a real question. – zero_cool Sep 26 '17 at 16:28
  • _I don't want to bind it via: `this.callMe(argToPass).bind(this)` b/c of performance issues._ -- You mean because that's not correct? Because unless `this.callMe()` returns a function, that would just throw an error, but even if it did, you'd still have a bug there. **Notice** I have not downvoted, I'm just commenting. – Patrick Roberts Sep 26 '17 at 16:28
  • There are performance issues, and I do not want to bind the function to the context of that component using that notation. Ref here: https://daveceddia.com/avoid-bind-when-passing-props/ – zero_cool Sep 26 '17 at 16:31

3 Answers3

5

The JS equivalent is Function#bind:

this.callMe.bind(this, argToPass)

btw - I suggest avoiding binding the function in the props in the render phase. You can read more about it in Why shouldn't JSX props use arrow functions or bind?

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • I do not want to bind in the onClick. Is this the same as this.callMe(argToPass).bind(this)? – zero_cool Sep 26 '17 at 16:29
  • 1
    You asked for the equivalent of `_.bind()`, and Function#bind it is. Binding in react is a different subject, and you should check the link I've added to the answer. – Ori Drori Sep 26 '17 at 16:32
0
onClick = {() => this.callMe(arrtopass)}

Try this.it's es6 sentax.

Dhaval
  • 1,393
  • 5
  • 29
  • 55
0
import partial from 'lodash/partial'

// bind using Function.bind
onClick={partial(this.callMe.bind(this), argToPass)}

// when binded in constructor or using arrow function
onClick={partial(this.callMe, argToPass)} 
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Michael Dodd Sep 27 '17 at 16:50