Normoney123
Normoney123

Reputation: 59

Function in my class is always getting called on page load, when I only want it called onClick

I have a function that I want to call only onClick. However it's getting called right when the page loads, and then the onClick doesn't call it again afterwards.

handleIncrement() is what I'm trying to call, that's being called on load, and the button in render is where I'm trying to have it called onClick.

class Counter extends Component {
  state = {
    count: 0
  };

  handleIncrement() {
    console.log("Increment Clicked", this.state.count);
  }

  render() {
    return (
      <div>
        <span style={{ fontSize: 20 }} className={this.getBadgeClasses()}>
          {this.formatCount()}
        </span>
        <button
          onClick={this.handleIncrement()}
          style={{ fontSize: 25 }}
          className="btn btn-secondary btn-sm 30"
        >
          Increment
        </button>
      </div>
    );
  }

  getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const { count } = this.state;
    return count === 0 ? "Zero" : count;
  }
}

Upvotes: 0

Views: 49

Answers (2)

Fortu.Y
Fortu.Y

Reputation: 66

onClick={this.handleIncrememt}

Upvotes: 0

ford04
ford04

Reputation: 74500

Change it to onClick={() => this.handleIncrement()}

Upvotes: 2

Related Questions