Table of Contents

About

React is a virtual dom library that:

  • permits to define the HTML dom programmatically
  • will update HTML dom incrementally

Step by Step: The Welcome element

There is basically two big steps when you work with React (or any virtual dom library)

Creating a React element

In the below code, you see:

function Welcome(props) {
  return React.createElement(
     'h1',  // the type of element (html element type)
     {},  // the props (html such as element can get attribute such as  class)
     [ // the children of the element build the DOM tree
        `Hello, ${props.name}`, // the first child is a text node
        props.children // the other node passed with the arguments
     ]
     );
}

Composing them to create the DOM Tree

You can compose the element to create the React DOM Tree. Below we define our top node of the tree:

  • with a welcome element
  • that accepts a welcome element as child
const MyRootNode = Welcome( 
    { 
        name:"Bar",
        children: Welcome({name:"Foo"})
    }
);

Rendering

The React Library

The react library 1)needs to be present.

<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

The HTML container

To render in a HTML page, React needs to now where to put the HTML that it will create.

This html element is generally a div called the root Id.

In your HTML page:

<div id="root"></div>

The Render function

The creation of the HTML (rendering) is done via the ReactDOM.render that takes two parameters:

ReactDOM.render(
  MyRootNode,
  document.getElementById('root')
);

Result

The above rendering function will output:

If you inspect the generated HTML DOM, you will see:

<h1>Hello, Bar
    <h1>Hello, Foo</h1>
</h1>

Hello World in Jsx

You can write your javascript in jsx

making your code less verbose.

The above React Element written in JSX would become:

  • The definition of Welcome tag in Jsx
function Welcome(props) {
  return <h1>Hello, {props.name} {props.children}</h1>;
}
  • The root node
const MyRootNode = 
<Welcome name="Foo">
    <Welcome name="Bar"></Welcome>
</Welcome>;
  • Output:

Documentation / Reference