RetroMime
RetroMime

Reputation: 387

MenuItem click event targeted at render

Im upset and I'm hating React because I make one step ahead on two behind. Now the problem is the method onCLick event of a MenuItem that is targeted at render time and not when I effectively click the menu.

MenuItem is inside a Drawer component:

<Drawer
  open={this.props.state_open_list_dash}
  openSecondary={true}
  docked={false}
>

with:

 <MenuItem 
    onClick={ this.handleChangeDash() }> Menu Name 
 </MenuItem>

In the constructor:

this.handleChangeDash = this.handleChangeDash.bind(this);

and then:

handleChangeDash ()
{     
   console.log(20);
}

The "20" on console is printed (3 times) at app refresh and (2 times) when the Drawer is opened due to an click event that change state_open_list_dash.

I have ended the ideas. Searching on web I've not found anyone with this problem so Im worried.

THanks

Upvotes: 2

Views: 10719

Answers (1)

Ahsan Ali
Ahsan Ali

Reputation: 5135

It's because you're invoking the function onClick={ this.handleChangeDash() } at the runtime.

Change it to:

 <MenuItem 
    onClick={ this.handleChangeDash }> Menu Name 
 </MenuItem>

or you can make an arrow function like so

 <MenuItem 
    onClick={ () => this.handleChangeDash() }> Menu Name 
 </MenuItem>

onClick will automatically invoke it when the event will happen.

Upvotes: 6

Related Questions