I have a bug in my React code where a component needs to locate an element on the page, but that element is not yet rendered.
The render method that handles calling both these components looks like this:
render() {
const generatedId = "myComponent123"
return (
<ParentComponent generatedId={generatedId}>
<ChildComponent generatedId={generatedId} />
<ParentComponent/>
)
}
ParentComponent
renders its children:
render() {
return (
<div id={this.props.generatedId}>
{this.props.children}
</div>
)
}
And ChildComponent
needs to locate its parent component in order to set a style:
render() {
const myParentsScrollPosition = getWindow().document.getElementById(
this.props.generatedId
).scrollTop;
return (
<div style={{ top: `${myParentsScrollPosition}px` }}>
...
</div>
);
}
The problem I am having is that both these components get rendered async and thus when ChildComponent
checks .getElementById(this.props.generatedId)
that element doesn't exist. It's still rendering.
How can I make ChildComponent
wait until ParentComponent
has rendered and therefore will be available in the DOM?
Alternatively I am thinking of other solutions but I'm not sure. For example, could I wait for the parent to mount before rendering the children, thus assuring it will always be available in the DOM?