React - Getting Started (The Welcome Element)
Table of Contents
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)
- You write your React DOM element (ie the equivalent of HTML element) with the createElement function.
Creating a React element
In the below code, you see:
- A html h1 react element created with the create element function (in the welcome function)
- A Welcome user defined react element (also known as component) that accepts arguments (called props)
- making the h1 text dynamic with a name
- allowing to add children
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/[email protected]/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/[email protected]/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:
- a React element (component, html element). We pass our root node but you can pass any other element.
- The HTML node where to add the generated HTML (in our case root)
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
- to replace the create element function.
- by markup xhtml notation
making your code less verbose.
You need to transpile it in native javascript with babel
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: