user3645925
user3645925

Reputation: 121

react calling function in onclick all the time

So I am using reactjs and node to make a website. In this one component that is meant to be a login button, it keeps track of whether the user is logged in or not using another class/object I have defined elsewhere. The problem is that I set it to call a logout function on click when the person is logged in (as well as say logout instead of login) but this onClick function is triggering instantly upon the button being clicked once.

class LoginButton extends React.Component {
  render() {
    if (AuthService.isAuthed() === false) {
      return (
        <li className="menu_button">
          <Link to="/login">Login</Link>
        </li>
      );
    } else {
      return (
        <li className="menu_button">
          <a href="/" onClick={console.log('Attempted to logout!')}>
            Logout
          </a>
        </li>
      );
    }
  }
}

I changed the logout function to just a console.log() to know everytime its being called.

Upvotes: 0

Views: 663

Answers (1)

audeos
audeos

Reputation: 336

Your onClick method needs to be a function, not the result of executing a function. Something like:

function onClick() {
    console.log("Attempted to logout!")
}

<a href="/" onClick={ onClick }>

In ES-6 you could do

<a href="/" onClick={ () => console.log("Attempted to logout!") }>

Upvotes: 4

Related Questions