Understanding JSX Syntax and HTML Differences
Understanding JSX Syntax and HTML Differences
1. What is JSX?
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML-like markup directly inside your JavaScript files. While it visually resembles HTML, JSX possesses the full expressive power of JavaScript.
Browsers cannot natively execute JSX. Before reaching the browser, build tools (such as Vite's Babel or esbuild transforms) compile JSX markup into standard JavaScript function calls (React.createElement or the modern JSX runtime jsx() / jsxs() functions).
JSX Code:
Transpiled JavaScript Output:
2. Key Differences Between JSX and HTML
Because JSX is transpiled into JavaScript objects and interacts with the DOM's JavaScript properties rather than HTML attributes, several critical syntax differences must be respected:
| HTML Attribute | JSX Equivalent | Reason / Rationale |
|---|---|---|
class | className | class is a reserved keyword in JavaScript for defining classes. |
for | htmlFor | for is a reserved keyword in JavaScript for for loops. |
tabindex | tabIndex | JSX attributes follow standard camelCase naming conventions. |
onclick | onClick | React uses camelCase synthetic event handlers. |
style="color: red;" | style={{ color: 'red' }} | Styles must be passed as JavaScript objects, not raw strings. |
<input> (unclosed) | <input /> | All elements must be explicitly closed in JSX. |
3. Strict Syntax Rules of JSX
Rule 1: Return a Single Root Element
A component cannot return multiple top-level sibling elements without wrapping them in a single parent container (such as a <div> or a <React.Fragment> / <>):
Rule 2: Close All Tags
In HTML, void tags like <img>, <input>, <hr>, and <br> can be left unclosed. In JSX, every tag must be explicitly closed:
Rule 3: CamelCase Most Properties
Almost all attributes and event handlers in JSX are written in camelCase (aria-* and data-* attributes remain hyphenated as in standard HTML):
Practice Quiz
className instead of the traditional HTML class attribute?<img> and <input>) be formatted in JSX?for attribute on <label> elements in JSX?data-*) written in JSX?Embedding JavaScript Expressions in JSX
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Virtual DOM and React Render Cycle Explained | Embedding JavaScript Expressions in JSX |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.