Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 132 ยท Getting Started

JSX Basics

Learn JSX from scratch - what it compiles to, curly-brace expressions, attributes like className and htmlFor, self-closing tags, fragments and how JSX differs from HTML.

JSX is the syntax that makes React code look like HTML written inside JavaScript. It is the first thing every React learner sees, and it is also the first thing that confuses them: it looks like markup, but it lives inside functions, takes JavaScript values in curly braces, and follows slightly different rules from HTML.

The good news is that JSX is small. There is no new programming language to learn, just a handful of rules. This lesson covers all of them, shows exactly what your JSX turns into, and lists where JSX differs from HTML. The next lesson, JSX in Depth, covers spreading props, conditional output and safety.

What JSX is

JSX stands for JavaScript XML. It is syntax sugar for creating React elements (the plain description objects from How React Works). A tool called a compiler, usually Babel, SWC or esbuild, rewrites every JSX tag into an ordinary function call before the browser ever sees it. In a normal project this happens in your build step; in our editors, Babel does it in the browser.

You are never forced to use JSX. It is simply a much nicer way to write the same thing:

JSX
// With JSX
const title = <h1 className="title">Hello</h1>;

// What the compiler turns it into (automatic runtime)
import { jsx as _jsx } from 'react/jsx-runtime';
const title = _jsx('h1', { className: 'title', children: 'Hello' });

Two takeaways. First, JSX is an expression: it has a value (an element object), so you can store it in a variable, return it from a function, pass it as an argument or put it in an array. Second, nothing about the tag is magic: <h1 className="title">Hello</h1> is a function call with a type ('h1'), props (className, children) and nothing else.

JavaScript inside curly braces

Plain text and tags are written as in HTML. To use JavaScript, wrap it in { }. Anything that is an expression (something that produces a value) is allowed: variables, arithmetic, function calls, ternaries, template literals, array.map(...).

Expressions in curly braces

Braces can appear in two places:

  • As content between tags: <h2>{formatName(user)}</h2>.
  • As an attribute value: <img src={user.photo} />. When the value is a JavaScript expression, use braces instead of quotes. Quotes mean a fixed string; braces mean a computed value. Do not write both.

Braces take expressions, not statements. You cannot put if, for or a variable declaration inside them. Do that work before the return, or use a ternary or .map inside the braces. A common mistake is putting a plain object where text is expected; we meet that error in JSX in Depth.

Where to put the JavaScript

A good habit: do calculations at the top of the component, then keep the returned JSX simple.

JSX
function Total({ prices }) {
  const total = prices.reduce((sum, price) => sum + price, 0);
  const label = total > 100 ? 'Free shipping' : 'Shipping applies';

  return (
    <p>
      {label}: ${total.toFixed(2)}
    </p>
  );
}

Attributes: JSX uses JavaScript names

Because JSX is JavaScript, attributes become properties on a props object, and they follow DOM property names in camelCase. The common differences from HTML:

HTML JSX Why
class className class is a reserved word in JavaScript
for htmlFor for is a reserved word
tabindex tabIndex camelCase
onclick onClick camelCase, and it takes a function, not a string
style="color: red" style={{ color: 'red' }} style takes an object
maxlength maxLength camelCase
readonly readOnly camelCase

aria-* and data-* attributes keep their dashes (aria-label, data-id), because they are not valid JavaScript identifiers anyway, and SVG attributes such as stroke-width become strokeWidth.

Here are several in one place. The style prop needs two pairs of braces for a reason: the outer pair is the JSX "JavaScript here" brace, the inner pair is the object literal.

className, htmlFor, style and friends

Click the label text: the input gets focus, because htmlFor="email" links it to the input with id="email". Notice also the CSS property in the style object is backgroundColor, not background-color, and that a unitless number such as fontSize: 14 is turned into 14px. Strings are used when you need other units: width: '50%'.

If you write an attribute React does not know, such as class, the browser console in a development build warns you and suggests the right name. Treat the warning as a to-do item.

Self-closing tags and closing every tag

In HTML you can leave <br>, <img> and <input> unclosed. JSX is stricter: every tag must be closed. Elements with no children use the self-closing form, with a slash before the final >:

JSX
<br />
<img src="/samples/sunset.svg" alt="A sunset" />
<input type="text" />
<MyComponent />

Self-closing also works for your own components, and you will use it constantly. A component with no children is simply <Spinner />. A tag you forget to close is a syntax error from the compiler, not a silent mistake, which is a gift: the problem shows up at once.

One root: why you need a wrapper or a fragment

A function returns one value, so a component can return only one JSX root. Returning two siblings is a compile error. Run it and read the message, which names the fix:

Two roots in one return (fails on purpose)

The console shows: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>? You have two options:

  1. Wrap them in a real element such as <div>. This adds an extra element to the page, which can break CSS layouts (a flex or grid parent now sees one child instead of two) or table structure.
  2. Wrap them in a fragment, a wrapper that groups children and leaves no trace in the DOM.

The short syntax for a fragment is an empty tag, <>...</>. When you need to give the fragment a key (for example inside a .map), use the long form, <Fragment key={id}>, imported from react.

Fragments: grouping without extra elements

A <dl> may contain only <dt> and <dd> children (optionally grouped in <div>), so a <div> around each pair would produce odd structure. The keyed Fragment groups each term with its meaning and leaves the markup clean. The same trick fits table rows and any list where an extra wrapper is wrong.

The parentheses habit

Writing return followed by a new line makes JavaScript insert a semicolon after return, so your JSX would never be reached. That is why multi-line JSX is wrapped in parentheses:

JSX
function Wrong() {
  return
    <p>never reached</p>;   // returns undefined
}

function Right() {
  return (
    <p>this works</p>
  );
}

Parentheses are not part of JSX; they are ordinary JavaScript grouping that keeps return and the tag on the same logical line. Formatters such as Prettier add them for you.

What JSX compiles to

Seeing the compiled form removes the mystery. JSX tags become calls to jsx (one child or none) and jsxs (several children) from react/jsx-runtime, the entry points that Babel inserts for you automatically. You can call them yourself. The next example builds the same element twice, once with JSX and once by hand, and compares them.

JSX is just function calls

All three elements render the same paragraph. jsx and jsxs are the modern output of the compiler ("automatic runtime"), while createElement is the older form that an older toolchain produced with React.createElement. Because the automatic runtime inserts its own import, you do not have to import React just to write JSX any more. If you read an old tutorial that starts every file with import React from 'react', that line is no longer needed for JSX.

JSX is not HTML

JSX looks like HTML, but it is closer to a templating syntax for JavaScript. Differences that cause real bugs:

  • Names are camelCase DOM properties, not lowercase HTML attributes (see the table above).
  • Event attributes take functions, not strings: onClick={handleClick}, never onClick="handleClick()". Passing onClick={handleClick()} is a classic bug: it calls the function while rendering and passes the result.
  • Booleans: <input disabled /> is shorthand for disabled={true}. To turn it off, pass false, not the string "false" (a non-empty string is truthy).
  • Whitespace is collapsed differently. JSX removes whitespace at line starts and ends and blank lines. To keep a visible space between an element and a text on different lines, write {' '}.
  • Entities work, but not everywhere. &amp;, &lt; and &nbsp; in JSX text are decoded, but entities inside a quoted string in braces are not: {'&amp;'} prints the literal characters. Use {'ย '} or put the entity in the text.
  • Comments need braces: {/* like this */}, not <!-- -->.
  • Lowercase means DOM element, capital means component. <card /> renders a literal unknown HTML element called card; <Card /> renders your component.
  • The text is escaped. If a string contains <script>, React shows it as text; it never becomes markup. JSX in Depth explains the one escape hatch and why to be careful with it.

Forgetting to capitalize a component name is one of the most common beginner bugs. You get no error, just an empty or odd element in the DOM, because <product /> is treated as a built-in tag with that name.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the compiler turn a JSX tag like <h1 className="x">Hi</h1> into?

    JSX is syntax sugar for function calls from react/jsx-runtime (or createElement). The call returns a plain element object that React later turns into DOM.
  2. 2. Which attribute spelling is correct in JSX?

    Both class and for are reserved words in JavaScript, so JSX uses the DOM property names className and htmlFor.
  3. 3. Why do you write style={{ color: 'red' }} with two pairs of braces?

    The outer braces say JavaScript here; the value inside is an object literal, which is why you see double braces.
  4. 4. How do you return two sibling elements from a component without adding an extra DOM element?

    A fragment groups children and adds nothing to the DOM. A div works but changes the DOM structure.
  5. 5. What is wrong with <button onClick={save()}>Save</button>?

    save() is a function call, evaluated when the JSX is evaluated. Pass the function itself (onClick={save}) or wrap it in an arrow function.

Summary

  • JSX is syntax sugar for jsx(...) / createElement(...) calls that return element objects; a compiler rewrites it before the browser runs it.
  • Use { } for JavaScript expressions in text or attribute values; statements such as if and for do not fit inside braces.
  • Attributes use DOM property names in camelCase: className, htmlFor, tabIndex, onClick; style takes an object.
  • Every tag must be closed; use self-closing form for empty elements and components.
  • A component returns one root; use a fragment (<>...</> or keyed <Fragment>) to group siblings without an extra element.
  • Wrap multi-line JSX in parentheses after return, and capitalize component names.
  • JSX is not HTML: events take functions, comments need braces, text is escaped.

Next: JSX in Depth