My use case might be a bit different but thought it might be useful to post a solution I came up with as it takes a different approach.
Essentially I have a third party Popover component that takes an anchor DOM element as a prop. The problem is that I cannot guarantee that the anchor element will be there immediately because the anchor element becomes visible at the same time as the Popover I want to anchor to it (during the same redux dispatch).
One possible fix was to place the Popover element deeper into the component tree than the element it was to be anchored too. However, that didn't fit nicely with the logical structure of my components.
Ultimately I decided to delay the (re)render of the Popover component a little bit to ensure that the anchor DOM element can be found. It uses the function as a child pattern to only render the children after a fixed delay:
import { Component } from 'react'
import PropTypes from 'prop-types'
export default class DelayedRender extends Component {
componentDidMount() {
this.t1 = setTimeout(() => this.forceUpdate(), 1500)
}
componentWillReceiveProps() {
this.t2 = setTimeout(() => this.forceUpdate(), 1500)
}
shouldComponentUpdate() {
return false
}
componentWillUnmount() {
clearTimeout(this.t1)
clearTimeout(this.t2)
}
render() {
return this.props.children()
}
}
DelayedRender.propTypes = {
children: PropTypes.func.isRequired
}
It can be used like this:
<DelayedRender>
{() =>
<Popover anchorEl={getAnchorElement()}>
<div>Hello!</div>
</Popover>
)}}
</DelayedRender>
Feels pretty hacky to me but works for my use case nevertheless.