cubefox
cubefox

Reputation: 1301

how does the .render() function in react work internally?

I can define a component like this:

class Welcome extends React.Component {
  render() {
    return <h1>Hello!</h1>;
  }
}

When I want to render this object in the Dom (or rather add it to the virtual DOM) I call

ReactDOM.render(
  <Welcome />,
  document.getElementById('root')
);

That means that at some point multiple .render() functions are nested inside of each other since we defined return <h1>Hello!</h1>; inside of the .render() function of Welcome. It also means that I can use the .render() method to render an Object to the DOM and to define a new react object.

This syntax is from the official documentation

Does .render() just render things to the virtual DOM and the nesting is resolved by React internally or is there more behind it?

Upvotes: 4

Views: 1026

Answers (2)

cubefox
cubefox

Reputation: 1301

To understand render you have to understand how react works internally. To understand this in greater detail I would recoment reading this but here is a quick overview:

Conceptually a react component is a just a function that returns an Object like this:

{
  type: 'button',
  props: {...} 
};

So the render() part of a class component just specifies what part of the component will be returned. The react virtual dom is made up of many of these object nested inside of each other (in props.children). React will start at the top object, turn it into an html node and render it to the dom, then do the same for all of its children etc.

Upvotes: 1

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

From Rendering a Component:

(updated to reflect your code)

class Welcome extends React.Component {
  render() {
    return <h1>Hello!</h1>;
  }
}
ReactDOM.render(
  <Welcome />,
  document.getElementById('root')
);
  1. We call ReactDOM.render() with the <Welcome /> element.
  2. React calls the Welcome component with {} as the props.
  3. Our Welcome component returns a <h1>Hello!</h1> element as the result.
  4. React DOM efficiently updates the DOM to match <h1>Hello</h1>.

It may be beneficial to read up on the React Life Cycle.

Upvotes: 1

Related Questions