Search code examples
javascriptreactjscreate-react-app

react js call function from event


How do i call a function from a react component inside the same class, I'm using create-react-app BTW.

Somefunction(){ //function
 return true;
}

handleClick(e){ // this works
 Somefunction(); // but fails here as Somefunction is undefined
}

I think i'm not binding it correctly, why is it undefined ?

Thanks


Solution

  • Granted that you have bound the handleClick function to your class instance, you must access your Somefunction function on the instance with this.

    Somefunction() { 
      return true;
    }
    
    handleClick(e) {
      this.Somefunction();
    }