In React, rendering HTML is the fundamental process of displaying content on the browser. React uses JSX (JavaScript XML), which allows you to write HTML-like syntax within JavaScript. This makes it easier to structure and visualize the user interface (UI).
1. JSX Basics
JSX allows you to embed HTML directly into your JavaScript code. React uses JSX to render elements into the DOM.
Example:
import React from 'react'; import ReactDOM from 'react-dom'; const element = <h1>Hello, World!</h1>; ReactDOM.render(element, document.getElementById('root'));
Here:
element
is a JSX object representing an<h1>
HTML element.ReactDOM.render()
renders this element into theroot
DOM node.
2. Embedding Expressions in JSX
You can embed JavaScript expressions in JSX by wrapping them in curly braces {}
.
Example:
const name = "React"; const element = <h1>Welcome to {name} Tutorials!</h1>; ReactDOM.render(element, document.getElementById('root'));
3. Adding Attributes in JSX
JSX supports attributes similar to HTML but with slight differences:
- Use camelCase for attributes (e.g.,
className
instead ofclass
). - Use quotes for string values and curly braces
{}
for expressions.
Example:
const element = <img src="logo.png" alt="React Logo" />; ReactDOM.render(element, document.getElementById('root'));
4. Rendering Multiple Elements
To render multiple elements, you can:
- Wrap them in a single parent element like
<div>
. - Use React fragments (
<>
and</>
).
Example:
const element = ( <> <h1>Hello, React!</h1> <p>This is a simple example.</p> </> ); ReactDOM.render(element, document.getElementById('root'));
5. React Components and Rendering
React components are reusable pieces of UI. There are two types:
- Functional Components
- Class Components
Functional Component Example:
function Welcome() { return <h1>Welcome to React!</h1>; } ReactDOM.render(<Welcome />, document.getElementById('root'));
Class Component Example:
class Welcome extends React.Component { render() { return <h1>Welcome to React!</h1>; } } ReactDOM.render(<Welcome />, document.getElementById('root'));
6. Rendering Lists
React allows you to render lists dynamically using the .map()
method.
Example:
const items = ['Apple', 'Banana', 'Cherry']; const element = ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ); ReactDOM.render(element, document.getElementById('root'));
7. Conditional Rendering
React supports conditional rendering using standard JavaScript logic.
Example: Using if-else
:
function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back!</h1>; } return <h1>Please log in.</h1>; } ReactDOM.render(<Greeting isLoggedIn={true} />, document.getElementById('root'));
Example: Using Ternary Operator:
const isLoggedIn = true; const element = isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>; ReactDOM.render(element, document.getElementById('root'));
8. Using Inline Styling
React supports inline styles written as objects. The keys use camelCase syntax.
Example:
const style = { color: 'blue', backgroundColor: 'lightgray', padding: '10px', fontFamily: 'Arial' }; const element = <h1 style={style}>Styled with Inline CSS</h1>; ReactDOM.render(element, document.getElementById('root'));
9. Rendering HTML Directly from Strings (Dangerously)
React provides the dangerouslySetInnerHTML
property to render raw HTML. Use this carefully, as it may expose your app to XSS attacks.
Example:
const rawHTML = { __html: '<h1 style="color: red;">Hello, Raw HTML!</h1>' }; const element = <div dangerouslySetInnerHTML={rawHTML}></div>; ReactDOM.render(element, document.getElementById('root'));
10. Rendering with External Data
React often fetches data from APIs and renders it dynamically.
Example with useEffect
Hook:
import React, { useState, useEffect } from 'react'; function App() { const [data, setData] = useState([]); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => setData(data)); }, []); return ( <ul> {data.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> ); } export default App;
Key Points to Remember
- React uses Virtual DOM for efficient rendering.
- JSX is syntactic sugar for
React.createElement()
. - Always provide a unique
key
prop when rendering lists. - Avoid mutating props or state directly; use
setState
or hooks likeuseState
.
By understanding how to render HTML effectively with React, you can build dynamic, interactive, and efficient user interfaces.