React Render HTML
React’s purpose is to render HTML in a variety of ways on a web page.
React renders HTML to a web page using the createRoot() function and the render() method.
The createRoot Function
The createRoot() function accepts a single argument, an HTML element.
The function’s purpose is to define the HTML element that will display a React component.
The render Method
The render() method is then used to specify which React component should be rendered.
But where will the rendering take place?
Your React project’s root directory contains another subdirectory named “public”. This folder contains an index.html file.
The body of this file has only one <div>. Here is where our React application will be displayed.
Example
Display a paragraph inside an element with the id of “root”:
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(Hello
);
The result is displayed in the <div id=”root”> element.
It should be noted that the element id does not have to be “root”, however this is the common convention.
The HTML Code
The HTML code in this tutorial uses JSX, which allows you to write HTML tags within the JavaScript code:
Don’t worry if the syntax is strange; you’ll learn more about JSX in the following chapter.
Example
Create a variable that contains HTML code and display it in the “root” node:
const myelement = (
Name
John
Elsa
);
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(myelement);
The Root Node
The root node is the HTML element where you want to show the results.
It functions similarly to a React-managed content container.
It doesn’t need to be a <div> element or have the id=’root’:
Example
The root node can be called whatever you like:
Display the result in the <header id=”sandy”> element.
const container = document.getElementById('sandy');
const root = ReactDOM.createRoot(container);
root.render(Hallo
);