JSX
JSX
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like markup inside a JavaScript file. It was popularized by React to make writing UI components easier and more declarative.
How JSX Works
Under the hood, JSX is not valid JavaScript. Browsers don’t understand it. Before your code runs in the browser, a compiler like Babel transforms JSX into standard JavaScript function calls.
// What you write (JSX):
const element = <h1 className="greeting">Hello, world!</h1>;
// What Babel compiles it to (React 17+ JSX Transform):
import { jsx as _jsx } from "react/jsx-runtime";
const element = _jsx("h1", { className: "greeting", children: "Hello, world!" });
Core Rules of JSX
- Return a single root element: To return multiple elements from a component, you must wrap them in a single parent tag. You can use a
<div>or an empty wrapper called a Fragment (<>...</>). - Close all the tags: JSX requires tags to be explicitly closed. Self-closing tags must end in a slash (e.g.,
<img />instead of<img>). - camelCase all most things: JSX turns into JavaScript, and attributes written in JSX become keys of JavaScript objects. Since JavaScript has reserved words (like
class), you must useclassNameinstead. Attributes are written in camelCase (e.g.,strokeWidthinstead ofstroke-width).
Embedding Expressions
You can embed any valid JavaScript expression inside JSX by wrapping it in curly braces {}.
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>; // Renders: <h1>Hello, Josh Perez</h1>
You can use expressions for text, attributes, or even conditional rendering. However, you cannot put statements (like if or for loops) directly inside JSX braces; they must be evaluated beforehand or written using ternary operators and map functions.
Interview Questions
Q: What exactly is JSX under the hood?
A: JSX is a syntax extension for JavaScript. Browsers don’t understand JSX natively. During the build process (via Babel or SWC), JSX is compiled down to standard JavaScript function calls: React.createElement(type, props, ...children) (or the new _jsx runtime).
Q: Why do we have to use className and htmlFor in JSX instead of class and for?
A: Because JSX is fundamentally JavaScript, and class and for are reserved keywords in JavaScript. React uses camelCase property naming conventions that closely match the native DOM API properties.