Curriculum
Course: React
Login

Curriculum

React

Text lesson

React Render HTML

React’s primary goal is to render HTML on a web page, accomplished through the createRoot() function and its render() method.

The createRoot Function

The createRoot() function takes an HTML element as its argument to specify where a React component should be rendered.

The render Method

The render() method is used to specify which React component should be displayed.

So where does it render?

In the public folder of your React project, you’ll find an index.html file containing a single <div> element in the body. This <div> is where your React application will be rendered.

Example

Render a paragraph inside an element with the ID of “root”:

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root
.render(<p>Hello</p>);

The result appears in the <div id="root"> element.

<body>
 <div id="root"></div>
</body>
While the element ID does not have to be “root,” using this ID is a standard convention.

The HTML Code

This tutorial employs JSX, enabling you to write HTML tags directly within JavaScript code. If the syntax looks unfamiliar, you’ll get a better understanding of JSX in the next chapter.

Example

Define a variable with HTML code and render it in the “root” element:

const myelement = (
 <table>
    <tr>
      <th>Name</th>
    </tr>
    <tr>
      <td>John</td>
    </tr>
    <tr>
    <td>Elsa</td>
    </tr>
 </table>
);

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(myelement);

The Root Node

The root node is the HTML element where the React content will be displayed, essentially serving as a container for React-managed content.It doesn’t need to be a <div> or have the id='root'.

Example

You can name the root node whatever you prefer.

<body>

 <header id="sandy"></header>

</body>

Render the result inside the <header id=”sandy”> element:

const container = document.getElementById('sandy');
const root = ReactDOM.createRoot(container);
root.render(<p>Hallo</p>);