0
question = {
    quest : "How old am I?",
    answers : [17,18,20,25],
    correct : 17,
}

checkAnswer(){
    var usersAnswer = document.getElementById('ans-1').textContent;
    var answer = this.question.correct;
    if(usersAnswer==answer){
        alert('correct')
    }else{
        alert('u lost')
    }
}

With this code, i can't access object from event handler in ReactJS. I get this error :

TypeError: Cannot read property question of undefined P.S i'm begginer

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
Kim Ber
  • 69
  • 11
  • It's the classic `this` problem; 1. bind `this` to the functions or 2. use `checkAnswer = () => {` or 3. use `attribute={() => this.checkAnswer}` –  Mar 09 '19 at 16:25
  • Either use arrow functions or bind `this` to the function – Reda Meskali Mar 09 '19 at 16:25
  • 1
    Why are you using a DOM selector like that in a React component method? You should add your complete component code for us to fully understand what's going on here. – Andy Mar 09 '19 at 16:26
  • `this.checkAnswer = this.checkAnswer.bind(this);` – Reda Meskali Mar 09 '19 at 16:26
  • This is explained in the docs btw: https://reactjs.org/docs/handling-events.html (also, typing into the input field is supposed to update the `state`, which can then be used to compare to the answer. –  Mar 09 '19 at 16:27

1 Answers1

1

The error is due to wrong this binding. You can use Arrow Function

checkAnswer = () => {
    var usersAnswer = document.getElementById('ans-1').textContent;
    var answer = this.question.correct;
    if(usersAnswer==answer){
        alert('correct')
    }else{
        alert('u lost')
    }
}

You can also use Function.prototype.bind() instead of arrow function. You just need to add this.checkAnswer.bind(this). instead if this.checkAnswer.bind where you are setting the handler

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73