How do I do a synchronous ReactDOM.render

javascript, react-dom, reactjs

Solution

You can pass a callback to `ReactDOM.render(ReactElm, DOMNode, callback)`. The `callback` will be executed once the `ReactElm` gets loaded into the `DOMNode`.

Hope this helps!

function getDims(child) {
    var testEl = document.getElementById('test-el');
    ReactDOM.render(child, testEl, function(){
       var dims = testEl.getBoundingClientRect();
       ReactDOM.unmountComponentAtNode(testEl);
       return dims;
    }); 
}

Usage example:

class App extends React.Component{
  render(){ return <h1>Hello</h1>}
}
  
  ReactDOM.render(<App/>,
    document.getElementById('app'),
    () => console.log('Component Mounted'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Problem

For my app, I need to render some children, and then measure the resulting div. In pseudo code, it would look something like this: ``` function getDims(child) { var testEl = document.getElementById('test-el'); ReactDOM.render(child, testEl); var dims = testEl.getBoundingClientRect(); ReactDOM.unmountComponentAtNode(testEl); return dims; } ``` Unfortunately, according to the documentation ReactDOM.render may in the future become asynchronous. Is there a future-proof option to force synchronous rendering so the above function will work?

Original source