Using refs in react

React documentation contains the following warning:

Never refer to refs inside any component render method - or as long as any component render method even works anywhere in the call stack.

Why? My problem is that I am writing a component that expresses its children in ways that depend on the sizes of the children. That is, I need to measure the DOM nodes, so I need to access every child that I planned to do with refs in the render. What's wrong with that? Of course, I need to consider the fact that some children may not yet exist in the ref (there is no child in the first render).

By the way, my render seems to work.

+3


source to share


1 answer


Disclaimer: I'm not a Core React developer, but I use it quite extensively on a large project.

TL; DR: The safest place is to use lifecycle methods, in the method the .render()

component is still just a declarative description of what needs to be done.



Avoid what you create in your method .render()

is not the component to be displayed, it is a description of what you want to React for you. This construction happens later (when all the optimization comes in). At the same time, the object you returned to React.createClass

will be replaced by the new object. Render it the same way you send an email to React (an object posted to .createClass()

) and React responds with a package (component). If you need to do something with the subcomponents to be created, go to lifecycle methods . .refs

should be completed by the time .componentDidMount()

.

+4


source







All Articles