View Categories

React Render HTML

React’s core purpose is to efficiently render HTML onto web pages, making it a popular library for building dynamic user interfaces. This is achieved using the createRoot() function and its render() method.

The createRoot() Function #

The createRoot() function specifies the HTML element where the React application will be displayed. It accepts a single argument: the HTML element.

Example: Selecting the Root Element

const container = document.getElementById('root'); // Select the root element
const root = ReactDOM.createRoot(container); // Define React's rendering space

The render() Method #

Once the root element is defined, the render() method is used to display React components or elements within the root.

Where Does React Render? #

In your React project, the public/index.html file contains an HTML structure with a single <div> element, often with the ID "root". This is where the React application is rendered.

<body>
  <div id="root"></div> <!-- React renders here -->
</body>

Note: While “root” is the standard convention, you can use any ID for the root element.

Example: Rendering a Simple Element #

Here’s how you can render a paragraph inside the root element:

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

This results in the following HTML inside the <div id="root">:

<body>
  <div id="root">
    <p>Hello, React!</p>
  </div>
</body>

Rendering HTML Code with JSX #

React leverages JSX (JavaScript XML) to allow writing HTML tags within JavaScript code. This simplifies managing UI components.

Example: Rendering a Table

const myTable = (
  <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(myTable);

The above code generates an HTML table inside the root node.

Customizing the Root Node #

React’s root node isn’t limited to a <div> or an ID of "root". You can define any element and ID as your root node.

Example: Custom Root Node #

HTML:

<body>
  <header id="app-header"></header>
</body>

React Code:

const container = document.getElementById('app-header');
const root = ReactDOM.createRoot(container);
root.render(<p>Welcome to React!</p>);

The result will be displayed inside the <header id="app-header"> element.

Summary #

React uses the createRoot() function and render() method to inject HTML into your web pages. By leveraging JSX, you can seamlessly create dynamic components and render them into any root node you define. This flexibility is what makes React ideal for building interactive and efficient UIs.

Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!

Leave your comment