I'm using React v16.7 and I'm trying to inject React components into a third party JS library (namely, Highcharts) that requires me to return HTML from a function. Here's what I'm doing right now:
function tooltipFormatter(dataPoint) {
// ... Calculate props according to the dataPoint here ...
const mountPoint = document.createElement('div');
ReactDOM.render(<Tooltip {...tooltipProps} />, mountPoint);
return mountPoint.innerHTML;
}
And I pass this function in a configuration object, like so:
const config = {
...,
tooltip: {
...,
formatter() {
return tooltipFormatter(this);
}
}
}
The problem I'm having is that mountPoint.innerHTML
is empty. I found that ReactDOM.render()
sometimes works asynchronously:
ReactDOM.render()
currently returns a reference to the rootReactComponent
instance. However, using this return value is legacy and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the rootReactComponent
instance, the preferred solution is to attach a callback ref to the root element.
While debugging, I did this:
ReactDOM.render(<Tooltip {...tooltipProps} />, mountPoint, () => {
console.log(mountPoint.innerHTML); // non-empty
});
console.log(mountPoint.innerHTML); // empty
return mountPoint.innerHTML;
How can I coerce ReactDOM.render()
into working in a synchronous context? The puzzling thing is that return mountPoint.innerHTML
has worked in the rest of our application, but it seems that this case is the only place ReactDOM.render()
has chosen to render the contents asynchronously.