Getting Started
JSX Syntax
Understand JSX — the syntax extension that lets you write HTML-like code in JavaScript.
What is JSX?
JSX stands for JavaScript XML. It allows you to write HTML-like syntax directly in your JavaScript files.
JSX is not required in React, but it makes code much more readable and intuitive.
JSX Rules
- Every JSX element must be closed (self-closing or with a closing tag)
- JSX expressions must have one root element (or use a Fragment
<>) - JavaScript expressions go inside curly braces
{} - Use
classNameinstead ofclass(sinceclassis a JS keyword) - Use
camelCasefor HTML attributes:onClick,onChange
JSX is Transformed
Under the hood, JSX like <h1>Hello</h1> is transformed by Babel into React.createElement('h1', null, 'Hello').
Example
jsx
// JSX basics
const element = <h1>Hello, World!</h1>;
// Embedding expressions
const name = "React";
const greeting = <p>Welcome to {name}!</p>;
// Multi-line JSX (use parentheses)
const card = (
<div className="card">
<h2>Title</h2>
<p>Content goes here</p>
</div>
);
// Self-closing tags
const input = <input type="text" placeholder="Enter text" />;
// Fragments (no extra DOM node)
const list = (
<>
<li>Item 1</li>
<li>Item 2</li>
</>
);
// Conditional rendering
const isLoggedIn = true;
const message = (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
</div>
);Try it yourself — JSX