React - ReactDOM.render

About

ReactDOM.render 1) is the main function that renders initialy an element.

It will be:

Note that the rendering is updated when the state changes. See this page for more information about re-rendering: React - Rendering (Lifecycle)

Example

Javascript

In Native Javascript, you need to create the element of the virtual dom

// equivalent to `<h2>It is ...</h2>`
let h2 = React.createElement('h2', {key:2}, `It is ${new Date().toLocaleTimeString()}`); 
  • Second Node of the tree: A user element called also component (ie a function with a single object parameters called a props that returns an react element
let welcomeComponent = function (props) { return React.createElement(
    'h1', 
    {key:props.key,className: 'greeting'}, 
    `Hello, ${props.name}!`
    ); 
};
  • The root of the tree with its two children node
// equivalent to `<div><h1><h2> ...</h2></h1></div>`
let root = React.createElement('div',{},
                            [
                               welcomeComponent({key:1,name:"Foo"}), // the user component
                               h2 // the html element
                            ]
); 

// render
ReactDOM.render(root, document.getElementById('root'));
  • The HTML
<div id="root">
<!-- called the "root" DOM node because the rendering of the root node is done inside -->
</div>
  • Result:

When using jsx, the text and the javascript variable of the user component are split into two elements making potential update more granular

Jsx

jsx is a language that wraps Javascript and permits to create easily react element in a HTML declarative way.

Demo:

  • Rendering an element (jsx) at interval every second - The tree is created each time to fake an update of the state
function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(
    element,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>

Below React will modify only the time part

Note that the text It is is not modified as React split them in different element.

Multiple root

See the dedicated page

Documentation / Reference


Powered by ComboStrap