Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 18: how to force synchronous rendering?

After upgrading to React 18, I am having issues with Leaflet popup rendering.

It seems the new rendering function has become asynchronous, which breaks Leaflet popup display (because Leaflet needs to compute the size of the popup for positioning, but now it gets an empty content since React has not yet rendered the popup).

Before (working as expected):

marker.bindPopup(() => {
  var div = document.createElement('div');
  ReactDOM.render(<MyPopup />);
  console.log(div.innerHTML); // <div>[...]</div>
  return div;
});

With React 18 (positioning broken):

marker.bindPopup(() => {
  var div = document.createElement('div');
  createRoot(div).render(<MyPopup />);
  console.log(div.innerHTML); // empty string!
  return div;
});

Is there any way to force React 18 to render the popup before returning the div?

like image 555
piero-la-lune Avatar asked Jun 22 '26 08:06

piero-la-lune


1 Answers

I just found another solution that seems to be working, and better suited to a production environment: flushSync. In the React documentation, it is not mentioned for this purpose, only to opt out of automatic batching.

I still not sure if this is the correct way to do it, or if it will break in a future update.

marker.bindPopup(() => {
  var div = document.createElement('div');
  const root = createRoot(div);

  flushSync(() => {
    root.render(<MyPopup />);
  });

  console.log(div.innerHTML); // <div>[...]</div>
  return div;
});
like image 96
piero-la-lune Avatar answered Jun 24 '26 23:06

piero-la-lune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!