-1

Getting type error, but when I use onClick={()=>this.clickHandler()} works like charm. So what happened when I use onClick={()=>this.clickHandler()} and whay I am getting error by writing onClick={this.clickHandler}

enter image description here

constructor(props){
        super(props)
    }
    render() {
        return (
            <div>
                <button onClick={this.clickHandler}>Class click</button>
                {/* <button onClick={()=>this.clickHandler()}>Class click</button> */}
            </div>
        )
    }

    clickHandler(){
        this.logPrint()
    }
    logPrint(){
        console.log("click the button");

    }
Rafiq
  • 8,987
  • 4
  • 35
  • 35
  • Missing bind in react – xdeepakv Apr 01 '20 at 12:42
  • 5
    Does this answer your question? [Why and when do we need to bind functions and eventHandlers in React?](https://stackoverflow.com/questions/41113798/why-and-when-do-we-need-to-bind-functions-and-eventhandlers-in-react) – xdeepakv Apr 01 '20 at 12:42
  • https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function – Toivo Säwén Apr 01 '20 at 12:49

2 Answers2

2

Two ways to achieve this

Use arrow functions

clickHandler: () => {

}

Bind method with component's this in constructor

constructor(props){
    super(props);
    this.clickHandler = this.clickHandler.bind(this);
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
1

Use arrow functions for event handlers, they will bind this automatically:

clickHandler = () => {
    this.logPrint()
}