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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

or try to use arrow function instead of binding

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.