JSX Syntax Explained
JSX Syntax Explained
JSX is a syntax extension that writes HTML-like markup inside JavaScript. It is not required, but it makes your components readable and is the standard style in React tutorials and teams.
Elements and attributes
Compare a plain HTML element with its JSX version:
<img src="logo.png" alt="Logo" />
JSX preserves HTML attributes, with a few quirk differences. The class attribute becomes className, because class is a reserved word in JavaScript. Most other attributes keep their HTML names.
Embedding expressions
Wrap any JavaScript expression in curly braces to embed it:
const name = 'Ada';
const element = <h1>Hello, {name}</h1>;
Anything inside braces is evaluated. You can call functions, use variables, and compute values. Strings inside braces do not need quotes; quotes are only for literal attribute strings.
Rules to remember
Three rules keep JSX valid. First, return one root element. If you have siblings, wrap them in a fragment or a div. Second, close every tag, including void elements like img or input. Third, use camelCase names for attributes such as onClick and className.
JSX is an expression
JSX compiles down to JavaScript. Each JSX element becomes a call to React.createElement. That means you can store JSX in variables, pass it to props, and return it from functions. This flexibility is why JSX feels powerful beyond simple markup.
Key Points
- JSX writes HTML-like markup inside JavaScript.
- Return a single root element and close every tag.
- Use curly braces to embed JavaScript expressions.
- className replaces class and events use camelCase.
- JSX compiles to plain React.createElement calls.