Table of Contents

React - Getting Started (The Welcome Element)

About

React is a virtual dom library that:

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:

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.

You need to transpile it in native javascript with babel

The above React Element written in JSX would become:

function Welcome(props) {
  return <h1>Hello, {props.name} {props.children}</h1>;
}
const MyRootNode = 
<Welcome name="Foo">
    <Welcome name="Bar"></Welcome>
</Welcome>;

Documentation / Reference