1

In my app, I have a component with a state variable and a component variable in its constructor. However, if I try accessing them from my method by resizing the window, I get undefined and cannot read property 'test' of undefined.

import React from 'react';

class Testapp extends React.Component {

    constructor(props) {
        super(props);
        this.state = {test: "he"};
        this.test = "hu";
        window.addEventListener('resize', this.testCallback);
    }

    testCallback() {
        console.log(this.test);
        console.log(this.state.test);
    }

    render() {
        return( <p>Hello world</p> );
    }
}

export default Testapp;

How can I access these attributes from the method?

Jan Berndt
  • 913
  • 1
  • 10
  • 22

2 Answers2

3

Your function as is does not have access to the this variable in the correct context.

The easiest solution is to convert to an arrow function

testCallback = () => {
  console.log(this.test);
  console.log(this.state.test);
}

This will give your function the correct context of this.

Alternatively you could manually bind it in your constructor.

constructor(props) {
  super(props);
  this.state = {test: "he"};
  this.test = "hu";
  window.addEventListener('resize', this.testCallback);
  this.testCallback = this.testCallback.bind(this);
}
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
  • Ohhh, because a non-arrow-function already has its on `this`-context, right? – Jan Berndt Jan 20 '20 at 15:55
  • Here is a good answer that can explain things much better than I can https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Brian Thompson Jan 20 '20 at 15:56
0

Just use an arrow function instead. Alternatively, you can bind 'this' to the method.

Suraj Auwal
  • 322
  • 3
  • 9