React - Rendering (Lifecycle)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

rendering in React (ie update of the DOM)

Advertising

3 - Trigger

To make the UI interactive, you need to be able to trigger changes to your underlying data model.

3.1 - Root

The first rendering of the React DOM tree during a page load is done via the ReactDOM.render function

3.2 - Children Component

3.2.1 - state

A change of state trigger a changes of UI (ie will render the component again)

For:

setMyVariable("NewValue");
this.setState({ "whatever":"whatever"});

3.2.2 - props

A change of props does not trigger a changes of UI. props define the original state.

4 - Lifeycle

In React:

  • Rendering is called mounting
  • Removing is called unmounting
  • Updating is called updating

Lifecycle management is different by type of component syntax used. For:

Advertising

5 - Management

5.1 - Conditional

Conditional rendering with control flow statement (such as if, then else, … or the conditional (ternary) operator).

index.jsx
let button = null;
if (isLoggedIn) {
  button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
  button = <LoginButton onClick={this.handleLoginClick} />;
}

5.2 - No Rendering

The component must return null instead of its render output

5.3 - ReactDOM.render

ReactDOM.render is the main function that renders the root element

In practice, most React apps only call ReactDOM.render() once but you may use create and render several React DOM tree (for instance to integrate react at several place in another HTML application (php, ruby,…)

Example:

  • Rendering an element
index.jsx
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);
index.html
<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 nodes.

Advertising

6 - Documentation / Reference

web/javascript/react/render.txt · Last modified: 2019/06/21 14:58 by gerardnico