React Component Function not working onClick button

the component

constructor(props) {
   super(props);
   this.fuelD = props.fuelD; //array of objects
   this.state={
     averageFuelConsumption:0,
   }
}

the custom function

calcAverage = () => {
  console.log("something")
}

the button

<button onClick={()=>this.calcAverage)}>Click</button>

clicking the button .. resolves to nothing in the console... if I do this .. it works

<button onClick={()=>console.log("something")}>Click</button>

I tried bind(this) on the function

1.in the constructor() - not working

2.in the onClick - not working

Upvotes: 0

Views: 2853

Answers (4)

Patrick Gaskill
Patrick Gaskill

Reputation: 166

Change your button to either

<button onClick={this.calcAverage}>Click</button>

or

<button onClick={() => this.calcAverage()}>Click</button>

Currently, your onClick handler is just returning a reference to this.calcAverage, not actually calling it.

Upvotes: 1

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

There are two ways to solve this:

Solution 1

<button onClick={() => this.calcAverage()}>Click</button>

You missed the () in your code.

Should you need event (in case event.stopPropagation() is necessary, for example):

<button onClick={(event) => this.calcAverage(event)}>Click</button>

Solution 2

<button onClick={this.calcAverage}>Click</button>

This is the recommended one since using arrow function to bind the event (as in Solution 1) could cause performance issues in the future. Every time your component gets rendered it recreates the same event over and over.

Upvotes: 0

Carl Edwards
Carl Edwards

Reputation: 14464

Replace:

<button onClick={()=>this.calcAverage)}>Click</button>

With

<button onClick={this.calcAverage)}>Click</button>

In the former you're returning the reference of function within an anonymous function instead of invoking it.

Upvotes: 0

user268396
user268396

Reputation: 12006

You have a simple syntax error in onClick={()=>this.calcAverage)}. Note the closing paren ) which is unbalanced.

What you probably want is onClick={() => this.calcAlverage()}

Upvotes: 0

Related Questions