1

I got error of TypeError: Cannot read property 'offsetHeight' of undefined when trying to get offsetHeight of a dom node.

componentDidMount() {
        setTimeout(function(){
            console.log(this.contentBody.offsetHeight)
        },1000)
    }

I suspect this is caused my async where the ref is not yet set. My render method look like this

<div ref={elem => this.contentBody = elem} className="content-body" dangerouslySetInnerHTML={createMarkupFromReferenceContent()} />

I tried to create a non ajax demo here https://codesandbox.io/s/j46o2656vy and it worked. That's why I try the setTimeout hack above, but no luck. Any clue how to solve this?

Jenny Mok
  • 2,744
  • 9
  • 27
  • 58

2 Answers2

0

You have to bind this to setTimeout callback function. Like this:

componentDidMount() {
        setTimeout(function(){
            console.log(this.contentBody.offsetHeight)
        },1000).bind(this);
    }
Yash Kochar
  • 461
  • 6
  • 15
0

this reffers to the closest scope, so when you use it with a callback function this points to the callback function and not your object.

In EcmaScript2015 this can be fixed by using an arrow function:

componentDidMount() {
    setTimeout(()=>{
        console.log(this.contentBody.offsetHeight)
    },1000)
}

But this syntax is not supported in the old browsers (IE in particular)

But if you need cross-browser support just use a variable:

componentDidMount() {
    var self = this;
    setTimeout(function(){
        console.log(self.contentBody.offsetHeight);
    },1000)
}