P4.1: JSX and Virtual DOM
Welcome to React! Before we write components, we must understand the core engine of React: JSX (JavaScript XML) and the Virtual DOM.
Welcome to React! Before we write components, we must understand the core engine of React: JSX (JavaScript XML) and the Virtual DOM.
Lesson: p4-1-jsx
Welcome to React! Before we write components, we must understand the core engine of React: JSX (JavaScript XML) and the Virtual DOM.
JSX is a syntax extension for JavaScript that looks like HTML, but compiles down to standard JavaScript function calls. It allows you to write the layout of your user interface directly alongside your logic.
[!IMPORTANT] JSX is NOT HTML! Browsers do not understand JSX. A compiler like Babel or SWC converts JSX code into standard
React.createElement()function calls before it reaches the browser.
When you write this JSX code:
const element = <h1 className="title">Hello World</h1>;
It compiles down to this standard JavaScript:
const element = React.createElement(
'h1',
{ className: 'title' },
'Hello World'
);
To write valid JSX, you must follow three strict rules:
JSX elements must be wrapped in a single parent tag (like a <div> or a React Fragment <>...</>).
// ❌ INVALID
return (
<h1>Welcome</h1>
<p>To React</p>
);
// VALID
return (
<>
<h1>Welcome</h1>
<p>To React</p>
</>
);
All tags must be explicitly closed, including self-closing tags like <img>, <br>, and <input>.
// ❌ INVALID
<img src="logo.png">
<input type="text">
// VALID
<img src="logo.png" />
<input type="text" />
Since JSX compiles to JavaScript objects, HTML attribute names are mapped to camelCase JavaScript properties.
className instead of class.htmlFor instead of for.tabIndex instead of tabindex.You can embed any valid JavaScript expression (variables, functions, math) inside JSX by wrapping it in curly braces {}.
const username = "Manoj";
const element = <h1>Welcome back, {username}!</h1>;
React uses a Virtual DOM to make rendering fast. Instead of modifying the real browser DOM directly (which is slow), React follows a three-step process:
Time taken (ms) to update 1,000 list items dynamically.