React Render HTML

🧱 React Render HTML

React does not directly modify the browser DOM like traditional JavaScript. Instead, it renders HTML inside a root element using the ReactDOM library.


πŸ“Œ The Root Element (HTML)

In a React project, open public/index.html and you’ll find this element:

<div id="root"></div>

React will render your entire application inside this element.


πŸ“Œ Rendering HTML in React

React uses:

  • ReactDOM.createRoot() β†’ creates root object

  • .render() β†’ renders the component/UI into the DOM

Example:

import React from "react";
import ReactDOM from "react-dom/client";
const root = ReactDOM.createRoot(document.getElementById(‘root’));

root.render(<h1>Hello React!</h1>);


πŸ“Œ Using JSX to Render HTML

React doesn’t use plain HTML β€” it uses JSX (JavaScript XML), which looks like HTML but works inside JavaScript.

Example:

const element = (
<div>
<h1>Welcome!</h1>
<p>This is rendered using JSX.</p>
</div>
);
root.render(element);


🎯 Rules of JSX (Important)

βœ” Must return a single parent element

❌ Invalid:

root.render(
<h1>Hello</h1>
<p>React</p>
);

βœ” Valid:

root.render(
<div>
<h1>Hello</h1>
<p>React</p>
</div>
);

OR using a fragment (<>...</>):

root.render(
<>
<h1>Hello</h1>
<p>React</p>
</>
);

🧩 Rendering Variables

JSX allows inserting JavaScript values using {}:

const name = "Vipul";

root.render(<h2>Hello, {name}!</h2>);


πŸ” Rendering Functions

function greeting() {
return "Welcome to React!";
}
root.render(<h3>{greeting()}</h3>);


🧱 Rendering Component Instead of HTML

React usually renders components instead of plain HTML.

Example:

function App() {
return <h1>This is a component!</h1>;
}
root.render(<App />);


πŸŽ‰ Summary

React renders HTML using:

βœ” root.render()
βœ” JSX syntax
βœ” One parent container
βœ” Ability to embed JS values
βœ” Components for reusable UI

You may also like...