Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a synchronous ReactDOM.render

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?

like image 431
derekdreery Avatar asked Oct 29 '16 12:10

derekdreery


People also ask

Does React render synchronous?

React rendering is synchronous The virtual DOM is basically the Javascript representation of the user interface and is equivalent to the actual DOM. The only difference here is that the virtual DOM is not displayed so it's faster to manipulate.

Can we have two ReactDOM render?

In Vue and React, we can only render one element. Even if we have multiple elements to render, there can only be a single root element. This means if we want to render two or more elements, we have to wrap them in another element or component.

What does the ReactDOM render () method do?

The ReactDOM.render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.

Can you call ReactDOM render more than once?

render(<App />, domNode); React will display <App /> in the domNode , and take over managing the DOM inside it. An app fully built with React will usually only have one render call with its root component. A page that uses “sprinkles” of React for parts of the page may have as many render calls as needed.


1 Answers

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>
like image 164
Pranesh Ravi Avatar answered Oct 09 '22 05:10

Pranesh Ravi