Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is onClick triggering on render of component instead of when clicked?

I have this button console.log as a test and it is being triggered whenever I refresh the page instead of when I click a nav button. Let me know if you can see the problem with this code if you'll need more.

import React from 'react';
import SideNav from "react-sidenav";
var TeamActions = require('../actions/TeamActions');

export default class Nav extends React.Component {
  pushName(name) {
    TeamActions.setTeamName(name);
  }

  render() {
    return(
      <SideNav.Menu
        path="#"
        itemHeight="32px"
        styles={{margin: "0"}}
      >
        <SideNav.MenuItem
          itemKey="truck"
        >
        //this is where I'm using onClick
          <SideNav.ILeftItem
            className="fa fa-truck"
            onClick={console.log("hello")}
          >
              Boston Celtics
          </SideNav.ILeftItem>
        </SideNav.MenuItem>
like image 427
Username Avatar asked Aug 26 '15 15:08

Username


1 Answers

That's because you're actually calling the console.log function in your onClick handler, rather than just pointing to its reference. JSX compiles to plain JS, so anything between {} brackets will be evaluated. You need to just point to the function reference in your onClick, not call it.

It's slightly complicated with the fact that when using ES6 classes you need to bind to the current this, it isn't autobound for you like with the old style React.createClass syntax, but here's a quick example,

class MyComponent {

  onLinkClicked () {
    console.log('Clicked!')
  }

  render () {
    return (
      <a onClick={this.onLinkClicked.bind(this)}>Click me</a>
    );
  }
}
like image 178
Jed Richards Avatar answered Oct 22 '22 21:10

Jed Richards