React aims to render HTML on a web page efficiently. React achieves this by using a function called createRoot()
and its method render()
.
The createRoot
Function
The createRoot()
function accepts one argument, which is an HTML element. It specifies the HTML element where a React component will be displayed.
The render
Method
The render()
method is used to define the React component that should be rendered within the specified HTML element.
So, where does it render?
In your React project’s root directory, there is a folder named “public”. Within this folder, you’ll find an index.html
file. You’ll see a single <div>
in the body of this file. This is where your React application will be rendered.
Displaying a paragraph inside an element with the id of “root” EXAMPLE
const rootElement = document.getElementById('root'); const root = ReactDOM.createRoot(rootElement); root.render(<p>Hello World</p>);
The result is displayed in the <div id="root">
element:
<body> <div id="root"></div> </body>
Note that the element id does not have to be “root”, but this is the standard convention.
The HTML Code
HTML code in React often uses JSX, which allows you to write HTML tags inside JavaScript code. Don’t worry if the syntax looks unfamiliar; you’ll learn more about JSX in the next chapter.
Create a variable containing HTML code and display it in the “root” node EXAMPLE
const myElement = ( <table> <tr> <th>Person</th> </tr> <tr> <td>Mark</td> </tr> <tr> <td>Laurenz</td> </tr> <tr> <td>Drew</td> </tr> </table> ); const rootElement = document.getElementById('root'); const root = ReactDOM.createRoot(rootElement); root.render(myElement);
The Root Node
The root node is the HTML element where you want to display the result. It acts as a container for the content managed by React. It doesn’t have to be a <div>
element, and it doesn’t have to be named “root”.
The root node can be called whatever you like
<body> <header id="mochi"></header> </body>
Display the result in the <header id="mochi">
element:
const rootElement = document.getElementById('mochi'); const root = ReactDOM.createRoot(rootElement); root.render(<p>Hi there!</p>);