user7021848
user7021848

Reputation: 31

React: Uncaught TypeError: Cannot read properties of undefined

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?

Upvotes: 0

Views: 2126

Answers (2)

Piotr Glejzer
Piotr Glejzer

Reputation: 278

or try to use arrow function instead of binding

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

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

Upvotes: 0

Vitaliy Rayets
Vitaliy Rayets

Reputation: 2394

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

Upvotes: 1

Related Questions