How to make synchronous ReactDOM.render

For my application, I need to display some children and then measure the resulting div. In pseudocode, it looks 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 become asynchronous in the future. Is there a future-proof way to force synchronous rendering so that the above function works?

+5
source share
1 answer

You can pass the ReactDOM.render(ReactElm, DOMNode, callback) . callback will be executed after loading ReactElm 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> 
+2
source

Source: https://habr.com/ru/post/1258975/


All Articles