You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that lets you write HTML-like markup directly inside your JavaScript code. JSX is not required to use React, but it is the standard way React components are written because it makes the relationship between logic and UI structure immediately clear.
const element = <h1 className="greeting">Hello, world!</h1>;
This looks like HTML, but it is actually JavaScript. Behind the scenes, a tool like Babel transforms JSX into calls to React.createElement:
const element = React.createElement("h1", { className: "greeting" }, "Hello, world!");
You rarely need to write React.createElement manually because JSX handles it for you.
1. Return a single root element. A component's JSX must have one top-level element. If you need to return multiple elements without adding an extra DOM node, use a Fragment: <React.Fragment> or its shorthand <>...</>.
2. Close every tag. Unlike HTML, JSX requires all tags to be explicitly closed — including void elements like and
.
3. Use camelCase for attributes. Because JSX compiles to JavaScript, attributes that clash with JS reserved words are renamed: class becomes className, for becomes htmlFor, and event listeners like onclick become onClick.
Curly braces {} let you embed any JavaScript expression inside JSX:
const name = "Alice";
const element = <p>Hello, {name}!</p>;
const sum = <p>2 + 2 = {2 + 2}</p>;
You can call functions, reference variables, and use ternary operators — but not statements like if or for directly (use ternary or array methods instead).
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>}
</div>
);
}
The && operator is also common for short-circuit rendering: {isLoggedIn &&
Welcome!
} renders the paragraph only when isLoggedIn is truthy.Inline styles in JSX are objects, not strings:
const style = { color: "blue", fontSize: "18px" };
const element = <p style={style}>Styled text</p>;
Note the double curly braces when writing the object inline: the outer {} is the JSX expression delimiter, the inner {} is the JavaScript object literal.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.