1

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>
1
  • From that code, you don't really seem to be calling the function at all, there would even no reason for using an arrow function in jsx, as it is already bound... Commented Oct 17, 2018 at 18:14

4 Answers 4

6

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>
    );  
  }

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

1 Comment

Actually his login function is already an arrow function, probably through class properties (so it already bound to this context)
5

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

Comments

3

Because your syntax is wrong. Correct syntax is:

<a style={{cursor: 'pointer'}} onClick={this.login}> Log In </a>

Comments

3

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.