In handleIncrement method, “this” is referring to undefined

In the method handleIncrement() when I log “this” to console, it displays undefined.
Whereas getBadgeclasses() is also a method of the same class in which this refers to the parent class.
Why is it so? Is it because the handleIncrement method is called by onClick property or is there some other logic?

import React, { Component } from "react";

class Counter extends Component {
  state = { count: 2, tags: [] };

  handleIncrement() {
    console.log(this);
  }

  render() {
    return (
      <div>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={this.handleIncrement}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>
      </div>
    );
  }
  getBadgeClasses() {
    let classes = "badge m-2 bg-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const { count } = this.state;

    return count === 0 ? "Zero" : count;
  }
}

export default Counter;

Answer

Since there is no auto-binding of methods to itself,

You have 3 solutions(maybe more).

First approach by binding the method to itself. create the following line inside a constructor:

this.handleIncrement= this.handleIncrement.bind(this);

Second approach refactor the onClick as the following:

onClick={()=>this.handleIncrement}

Third approach change the function to an arrow function

handleIncrement = (e) => {...}

then change the button aswell to:

onClick={this.handleIncrement.bind(this)}

This link will be use full: React & Autobinding