Why does onClick fire when a component is rendered, and not when clicked?

I have this console.log button as a test, and it starts whenever I refresh the page, and not when I press the nav button. Let me know if you see a problem with this code, if you 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> 
+5
source share
1 answer

This is because you are actually calling the console.log function in the onClick handler, and not just pointing to its link. JSX compiles to regular JS, so a comparison will be made between the brackets {} . You just need to point to the function link in your onClick and not call it.

This is a little complicated by the fact that when using ES6 classes you need to bind to the current this , it is not autonomous for you using the old-style syntax React.createClass , but here is a quick example,

 class MyComponent { onLinkClicked () { console.log('Clicked!') } render () { return ( <a onClick={this.onLinkClicked.bind(this)}>Click me</a> ); } } 
+7
source

All Articles