Reputation: 303
When my application renders the function contained within my onClick event is invoked without reason. I have looked around at a few other posts and implemented their suggestion but without success.
My function
login = () => {
this.props.login();
};
onClick event inside an tag
<a style={{cursor: 'pointer'}} onClick={ () => this.login }> Log In </a>
Upvotes: 1
Views: 1121
Reputation: 276
Instead of just passing a reference to the click handler, you're passing an arrow function which is being invoked which is in turn calling the login function.
This should give you what you're after:
<a style={{cursor: 'pointer'}} onClick={ this.login }> Log In </a>
Check out the react handling events docs
Upvotes: 5
Reputation: 31
Try making the login function respond to an event login = (event) => {
, and adding event.preventDefault()
Also, I'm not sure if it'd actually matter, or it's a stylistic thing, but you could just try onClick={this.login}
Upvotes: 3
Reputation: 419
Because your syntax is wrong. Correct syntax is:
<a style={{cursor: 'pointer'}} onClick={this.login}> Log In </a>
Upvotes: 3
Reputation: 2638
You need to pass your lambda like this:
<a style={{cursor: 'pointer'}} onClick={ () => this.login() }> Log In</a>
Note the parenthesis. As you have it now the function is automatically invoked when the script runs/your component renders.
It is also worth noting that using JSX lambdas can cause performance problems because it creates a new function on every render. You could do the following instead to prevent the new function generation.
class MyComp extends React.Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
}
public function login(event) {
// do something
}
render() {
return(
<a onClick={this.login}>Log In</a>
);
}
}
Upvotes: 6