How to Render HTML in React?

react html render
10 November 2024

In the world of Front-End, the React library is one of the most popular solutions for building user interface applications. One of the first concepts learned in React is how to render HTML. This process allows you to insert HTML elements or combinations of them into web pages and then control them using React's compelling features.

React is primarily a JavaScript library for building user interfaces, but it also allows rendering HTML in a powerful and declarative manner. If you are somewhat familiar with JavaScript, working with React will feel quite natural and straightforward. With React, you can easily create UI elements in a modular way, and manage and control them through props and state.

Reusable components are one of the noteworthy features of React, allowing you to make your code more organized and maintainable. For example, you can create a module to display a simple greeting and then reuse it anywhere else in your project with ease. These modules are recognized in React as components.

To get started with React, you first need to use JSX. JSX is a syntax that allows you to write both HTML and JavaScript together. This is precisely how React enables you to render HTML effortlessly. Now, let’s take a look at a simple example that illustrates rendering HTML in React.

Simple React Code Example


import React from 'react';
import ReactDOM from 'react-dom/client';

function App() {
  return (
    <div>
      <h1>Hello World!</h1>
      <p>This is my first React program</p>
    </div>
  );
}

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

Code Explanation

import React from 'react'; – This statement imports the React library.
import ReactDOM from 'react-dom/client'; – This line imports the ReactDOM library, which is responsible for rendering React components to the actual DOM.
function App() { return (...) } – This is a simple functional component that returns HTML elements.
<div> <h1>Hello World!</h1> <p>This is my first React program</p> </div> – Here, the HTML elements that need to be rendered are written.
const root = ReactDOM.createRoot(document.getElementById('root')); – This creates a reference in the DOM where React elements will be rendered.
root.render(<App />); – This code renders the App component into the HTML element on the page.

FAQ

?

How can I add another element to this code?

?

Why should we use JSX?

?

How can I add CSS styles to this component?