Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  57] [ 4]  / answers: 1 / hits: 105648  / 8 Years ago, fri, february 5, 2016, 12:00:00

I have an element with a ref that is defined and ends up getting rendered into the page :



    <div ref=russian ...>
...
</div>


I want to access the DOM element properties like offset... or something. However, I keep getting undefined and I haven't the faintest idea why. After some searching it's clear that refs are only applicable to one file but I'm not using this anywhere besides this one page. I'm saying this to log it:



console.log('REFS', this.refs.russian);



What could be causing this?


More From » reactjs

 Answers
34

The correct place to work with refs is inside specific React lifecycle methods e.g. ComponentDidMount, ComponentDidUpdate



You cannot reference refs from the render() method. Read more about the cautions of working with refs here.



If you move your console.log('REFS', this.refs.russian); call to ComponentDidMount or ComponentDidUpdate lifecycle methods (assuming you are on React >= 14) you should not get undefined as a result.



UPDATE: also refs will not work on stateless components per the caution link above


[#63430] Wednesday, February 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tatyanna

Total Points: 552
Total Questions: 96
Total Answers: 96

Location: Cook Islands
Member since Thu, May 21, 2020
4 Years ago
;