I've been hitting the issue mentioned in this thread where, when using the ref callback the refs are updating AFTER componentDidMount
.
Apparently this can happen when you pass refs to elements that are being passed to a component as children, but I think I've exhausted all other options. I can't pass it to the component (ComponentOne
) directly as it's a Styled Component and as per the docs I get a reference to the React component instance, which AFAIK I can't access .current
on. Nor can I wrap the component in a basic HTML element as it's being used as a marker in 'google-map-react'
, which doesn't expect one.
As a workaround I'm trying to use the ref callback to update some data using this
, with the intention that it re-renders a child component which is being passed it via props.
Here's the code:
refCb = (ref, name) => {
const { x, y } = ref.getBoundingClientRect()
this.refsData[name] = {
x,
y,
}
}
render () {
<div>
<ComponentOne>
{
this.state.list.map((listItem) => {
return (
<div ref={(itemRef) => {this.refCb(itemRef, listItem.name)}}></div>
)
}
}
</ComponentOne>
<ComponentTwo
refsData={this.refsData}
/>
</div>
}
If I console log in both refCb
and the render method of ComponentTwo
, I can see that the refCb
log comes in last.
I would have expected the ComponentTwo
to re-render after, as this.refsData
gets updated and it's being passed as props.
Am misunderstanding the component lifecycle? Any pointers would be great, thanks!
CodePudding user response:
It won't rerender, or at least it won't be stable. You need to make some kind of state, instead of
this.refsData[name] = {
x,
y,
}
Otherwise component won't see change and won't be able to rerender.
CodePudding user response:
There may be a more elegant solution, but for anyone who hit's the same issue (which is very specific) I just managed to work around it by calling setState({}) in the google maps component's onZoomAnimationEnd prop