Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is React.render() callback called?

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?

like image 259
akula1001 Avatar asked Jun 04 '15 11:06

akula1001


People also ask

When render is called in React?

It is part of the React component lifecycle. Generally, it gets called by React at various app stages when the React component instantiates for the first time, or when there is a new update to the component state. Render does not take any arguments and returns a JSX.

Is render or componentDidMount called first?

The componentDidMount() method is called after the component is rendered. This is where you run statements that requires that the component is already placed in the DOM.

What does a render () method in Reactjs return?

React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.

How does React know when to re render?

React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.


1 Answers

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)

like image 151
Anthony Blackshaw Avatar answered Sep 21 '22 11:09

Anthony Blackshaw