Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  169] [ 2]  / answers: 1 / hits: 19006  / 9 Years ago, thu, june 4, 2015, 12:00:00
React.render(<MyComponent/>, mainNode, function() {
console.log('2');
});
console.log('1');


prints



2
1


Also, a scrollTop() in the callback does not work. It works if I call it after render() returns.



Is React.render() synchronous?



Is the DOM rendered when the function returns?



When is the callback called? What would I want to do in the callback?


More From » reactjs

 Answers
23

You can move the callback logic into the component you are mounting and then use the componentDidMount method for the first time the component is rendered to the DOM, and componentDidUpdate for subsequent updates/renders to the DOM. The component will be available in the real DOM via window.document or using the components getDOMNode method in both these methods.



This is not quite the same as a render callback per se. It's worth noting that if you're changing the state of the component you can also pass a callback function to the setState method for the component that will be applied once the components state has been updated (and any changes rendered to the DOM).



Having looked at the React source code to confirm - when rendering a new root node (as per your code snippet) into the DOM the process is synchronous and the callback (if passed) triggers immediately after (https://github.com/facebook/react/blob/master/src/renderers/dom/client/ReactMount.js lines 570-582)


[#66333] Tuesday, June 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andrewb

Total Points: 259
Total Questions: 124
Total Answers: 90

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
;