Reputation: 692
I created canvas element with ref="canvas" property.
When i try to get them in componentDidMount
:
componentDidMount = () => {
console.log(this.refs);
}
There is empty Object.
BUT, then i do
componentDidMount = () => {
console.log(this);
}
I see React element with non-empty 'refs' Object containing my canvas!
How can this happen?
Upvotes: 3
Views: 1231
Reputation: 11093
I think the problem is that you are setting the value of componentDidMount
to be a function that will evaluate in order to set the result of componentDidMount
. At the time, this.refs
isn't populated because the component is firing that function pre-render. However, by just logging this
, the console will eventually pick up the updated component so you can see refs
inside of it. Here is how you should structure the component:
componentDidMount() {
console.log(this.refs)
}
Does that make sense? You're doing the equivilent of this...
class Foo {
bar = () => {
console.log('I get called when foo loads to determine the value of bar')
}
}
instead of this
class Foo {
bar() {
console.log('I get called with bar()')
}
}
I'm not able to actually test my code as this syntax is invalid, so I'm not sure how it's working for you...
Upvotes: 2