React is a virtual dom library that:
There is basically two big steps when you work with React (or any virtual dom library)
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
]
);
}
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"})
}
);
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>
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 creation of the HTML (rendering) is done via the ReactDOM.render that takes two parameters:
ReactDOM.render(
MyRootNode,
document.getElementById('root')
);
The above rendering function will output:
If you inspect the generated HTML DOM, you will see:
<h1>Hello, Bar
<h1>Hello, Foo</h1>
</h1>
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>;