0

I face a question as flow:

class App extends React.Component {

  testop(){
    alert("test");
  }

  showAlert() {
    // alert("Im an alert");
    this.testop();
  }
  

  render() {
    return <button onClick={this.showAlert}>show alert</button>;
  }
}

when I run the code, the error is "Uncaught TypeError: Cannot read properties of undefined (reading 'testop')". why cannot read testop function?

  • 1
    Does this answer your question? [Cannot read property 'bind' of undefined. React.js](https://stackoverflow.com/questions/39632811/cannot-read-property-bind-of-undefined-react-js) – Royi Namir Apr 24 '22 at 11:02

2 Answers2

1

The problem is that the this you are referring to inside showAlert is not referring to component's this instead it is referring to the internal methods this.

There are two solutions for this problem.

Either bind the function with component's this inside the component's constructor:

constructor (){
  this.showAlert = this.showAlert.bind(this);
}

Or use ES6's arrow function which provides lexical scoping

Vitaliy Rayets
  • 2,299
  • 1
  • 6
  • 12
0

or try to use arrow function instead of binding

showAlert = () => {
  this.testop();
}

https://codesandbox.io/s/tender-ully-1ynyqm?file=/src/App.js

Piotr Glejzer
  • 278
  • 3
  • 13