5

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>

1 Answer 1

7

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>
    );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, so it no longer fires on render but it is not firing when the button is being clicked either. Do you know where I should place the onClick to make it fire?
I can't be sure without seeing your code. Have a read of these docs they may help facebook.github.io/react/blog/2015/01/27/…

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.