Andrew Font Andrew Font - 16 days ago 5
React JSX Question

React: Can't call prop function when it is inside of another function?

I am trying to move over the Auth0 login function as described in their tutorial. I am able to get it work if I use it like this:

<button className="btn" onClick={this.props.route.auth.login.bind(this)}>test</button>


but if I set up the button to call a function I define above the render function like this:

login() {
this.props.route.auth.login.bind(this);
}


And change the onclick to be like this:

onClick={this.login()}


or

onClick={() => this.login()}


Then the auth login modal never opens and i receive no error. Also i added a
console.log
to
login()
and I can see it in the console, but the actual login modal never opens? It works in the first example, but not in the others.

The reason I am attempting to move this into a function is because I would like to pass the login function down into a child component later, and I was unable to do so and I believe this to be the root issue thats preventing me.

Answer

bind does not call your function:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. docs

Also, you are setting the value of onClick prop to the return value of login. If you want to pass a reference to the function, you have to do it without the ().

Your code should look like this:

<button className="btn" onClick={() => this.login()}>test</button> <!-- You need to keep a reference to `this`, hence the binding -->

Then:

login() {
   this.props.route.auth.login();
}

I edited the answer so that it uses an arrow function. However, I prefer not doing that, since it makes the code a bit cumbersome, and rather bind all the functions in the constructor, like @patrick-w-mcmahon did.