React: Losing ref values React: Losing ref values reactjs reactjs

React: Losing ref values


See the react documentation here, with important warnings and advise about when to use or not to use refs.

Note that when the referenced component is unmounted and whenever the ref changes, the old ref will be called with null as an argument. This prevents memory leaks in the case that the instance is stored, as in the second example. Also note that when writing refs with inline function expressions as in the examples here, React sees a different function object each time so on every update, ref will be called with null immediately before it's called with the component instance.


I'm not sure if this answers @be-codified's question for not, but I found this running into a similar issue. In my case, it turned out that it was due to using a functional component.

https://reactjs.org/docs/refs-and-the-dom.html#refs-and-functional-components

Refs and Functional Components You may not use the ref attribute on functional components because they don’t You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state.
You can, however, use the ref attribute inside a functional component as long as you refer to a DOM element or a class component

The documentation explains what you should do to solve the issue if you have control of the component you're trying to render.

However in my case, the component was from a 3rd party library. So, simply wrapping the component worked fine.

Working

<div ref={element => this.elementName = element}>    <FunctionalComponent /></div>

Not Working
sets this.elementName to null

<FunctionalComponent ref={element => this.elementName = element} />

Hope this helps anyone finding this question like I did.