1.5 Hours beginner
19. JSX (The Syntax)
JavaScript XML (JSX)
React fundamentally changes how we think about web development. Instead of keeping HTML in one file and JavaScript in another, React combines them. JSX is a syntax extension that allows you to write HTML-like markup directly inside your JavaScript files.
It Looks Like HTML, But It Is JavaScript
Browsers do not understand JSX natively. Before your code reaches the browser, build tools (like Vite or Babel) translate your JSX into standard JavaScript functions.
// You write this JSX:
const element = <h1>Hello World</h1>;
// The compiler turns it into this plain JavaScript behind the scenes:
// const element = React.createElement('h1', null, 'Hello World');
Embedding JavaScript in JSX
Because JSX is JavaScript under the hood, you can inject dynamic data, variables, or math directly into your markup using curly braces {}.
const username = "Prince";
const currentYear = new Date().getFullYear();
// We open a "JavaScript window" inside the HTML using {}
const greeting = (
<div>
<h1>Hello, {username}!</h1>
<p>The year is {currentYear}</p>
<p>Math works too: 2 + 2 = {2 + 2}</p>
</div>
);
The Strict Rules of JSX
JSX is stricter than standard HTML. You must follow three core rules:
- Return a single root element: A component cannot return two sibling tags. You must wrap them in a parent
<div>or an invisible Fragment<></>. - Close all tags: Tags like
<img>or<input>must be explicitly self-closed like<img />. - camelCase all attributes: Because
classis a reserved word in JS, you must useclassNameto add CSS classes. Event handlers likeonclickbecomeonClick.
Knowledge Check
Ready to test your understanding of 19. JSX (The Syntax)?