Thuta Learning
React
BasicWeb DevelopmentIntermediate

What is JSX?

ReactLesson 425 min

What you'll walk away with

  • Explain how a JSX tag becomes a React element object
  • Know that { } accepts expressions (variables, calls, ternaries) but not if or for statements
  • Convert HTML to JSX correctly with className, htmlFor, camelCase attributes, style objects and self-closing tags
  • Predict how strings, numbers, booleans, null, arrays and objects render

Explain it simply

Explain it simply

JSX is a syntax that lets you write HTML-like markup inside JavaScript. When you write <h1>Hello</h1>, it is neither a string nor real HTML: it is a JavaScript expression that React understands as a description of UI.

To bring JavaScript values back into the markup, you open a window with curly braces { }. In <h1>Hello, {name}!</h1>, the value of the name variable appears where the braces are. That keeps data and UI connected in one place.

Problem → Why → Solution

The problem: pasting HTML into a component breaks it

Imagine copying a sign-up form from a design template straight into a component's return. The markup worked fine in an HTML file, yet Vite reports compile errors: an unclosed tag, two elements side by side, a style string it refuses. React also warns about class and for.

SignUp.jsx
function SignUp() {
  return (
    <!-- sign-up form -->
    <h2 class="title">Join us</h2>
    <label for="email">Email</label>
    <input id="email" type="email">
    <p style="color: gray">We never share your email.</p>
  );
}

Why doesn't plain HTML work?

Under the hood JSX is JavaScript. Each tag becomes a function call and each attribute becomes an object property. A function returns one value, so there must be one root element. Every tag must be closed, style must be an object rather than a string, and class and for are written as the DOM property names className and htmlFor. JSX does not know <!-- --> comments either.

Core concept: JSX becomes element objects

When Vite compiles JSX, <h1 className="title">Hello, {name}!</h1> becomes a call to jsx() or jsxs() from react/jsx-runtime. The first argument is the tag type ("h1"); the second is a props object holding the attributes and the children. The call returns a small object shaped like { type: "h1", props: {...} }, which is a React element. Because JSX is an expression, you can store it in a variable, return it from a function or pass it as an argument.

Inside braces you may write only an expression, something that produces a value: a variable, arithmetic like price * qty, a call like name.toUpperCase(), a ternary cond ? a : b, cond && <X />, or items.map(...). Statements such as if, for or a const declaration produce no value, so they cannot go inside braces; put them above the return instead. For attribute values, use quotes for strings and braces for everything else: numbers, booleans, variables and objects.

Value inside bracesWhat renders
"text", 42The text "text", "42"
true, false, null, undefinedNothing at all
0 (from count && ...)The character "0"
["a", "b"] or an array of JSXEach item in order
An object like { name: "a" }Error: Objects are not valid as a React child

Remember five rules where JSX differs from HTML. (1) There is exactly one root element; use a fragment <>...</> when you do not want a wrapper div. (2) Every tag is closed, including <input /> and <img />. (3) class becomes className and for becomes htmlFor. (4) Attributes such as onclick and tabindex are camelCase: onClick, tabIndex. (5) style takes an object, as in style={{ fontSize: 18 }}: the outer braces open JavaScript, the inner ones are the object.

JSX inserts strings from braces as text, never as HTML. So if a user writes a comment containing <script>, it appears on the page as harmless text.

Mental model: tag, call, object
  1. You write <tag attr={x}>child</tag>
  2. The compiler emits jsx("tag", props)
  3. You get a { type, props } object
  4. React turns that object into DOM

Braces are a window into JavaScript, and only value-producing expressions fit through it.

General pattern

jsx
return (
  <>
    <tag className="css-class" attrName={expression}>
      Text and {expression}
      {condition ? <A /> : <B />}
    </tag>
    <selfClosing style={{ cssProperty: value }} />
  </>
);

The fragment <>...</> provides a single root without adding an extra DOM element. Quotes for string attributes, braces for everything else, a ternary to choose, a style object and self-closing tags are the shapes you will use every day.

Example: variables and a ternary inside JSX

The Greeting component declares two pieces of data, name and isLearning, above the return and uses them in the JSX through braces. Before running it, predict which text appears if you change isLearning to false.

jsx
function Greeting() {
  const name = 'Aung Aung';
  const isLearning = true;

  return (
    <section>
      <h1>Hello, {name}!</h1>
      <p>{isLearning ? 'Learning React' : 'I will start later'}</p>
    </section>
  );
}

Code breakdown

  1. Lines 2-3const name = 'Aung Aung';

    The data is declared with plain JavaScript above the return. Statements belong here, not inside JSX braces.

  2. Line 5return (

    When JSX spans several lines, the opening ( must sit on the same line as return. Writing return alone and starting the JSX on the next line makes JavaScript return undefined, and nothing renders.

  3. Line 6<section>

    <section> is the single root element wrapping both <h1> and <p>. If you do not need a wrapper, a <>...</> fragment works too.

  4. Line 7<h1>Hello, {name}!</h1>

    'Aung Aung' fills the {name} slot and joins the surrounding text to form "Hello, Aung Aung!".

  5. Line 8{isLearning ?

    A ternary is an expression that produces a value, so it fits inside braces. isLearning is true, so the first string is chosen; an if statement here would be a syntax error.

You should see
The browser will show the text `Hello, Aung Aung!` and `Learning React`.

What JSX really turns into

Calling the function the compiler emits shows that JSX is just an ordinary JavaScript object. This code runs in Node.js with no JSX at all. You never need to write this in your components; it is only here to make the idea concrete.

compiled.mjs
import { jsx, jsxs } from "react/jsx-runtime";

const name = "Aung Aung";

// What <h1 className="title">Hello, {name}!</h1> compiles to:
const element = jsxs("h1", { className: "title", children: ["Hello, ", name, "!"] });

console.log(element.type);
console.log(element.props);

// A single child uses jsx() and children is not an array
const note = jsx("p", { children: "Learning React" });
console.log(note.props.children);

In real projects

In real projects

Production code constantly switches className based on state, for example className={isActive ? "tab tab--active" : "tab"} to highlight the active tab. Projects using Tailwind CSS put long lists of utility classes in className. Inline style objects are usually reserved for values computed at runtime, such as a progress bar's width: percent + "%", while everything else stays in CSS files.

JSX's automatic escaping matters for security. Showing user-written content such as comments, reviews or chat messages with {comment.text} displays any HTML tags as text, which protects against script injection (XSS). There is a prop called dangerouslySetInnerHTML for showing real HTML from a CMS, but as the name warns, use it only with sanitised HTML.

Common mistakes

Common mistakes

1. count && ... rendering a stray 0

In {count && <b>New</b>}, a count of 0 makes && return 0, and since React renders numbers, a "0" appears on the page. Compare first so the left side is a boolean: {count > 0 && <b>New</b>}.

2. Rendering an object as a child

Putting a whole object in braces, as in <p>{user}</p>, throws "Objects are not valid as a React child". Pick a property such as {user.name}. A Date object also needs converting to a string, for example with date.toLocaleDateString().

3. Writing if inside braces

{if (isAdmin) { <Admin /> }} is a syntax error because if is a statement that produces no value. Use a ternary or && inside JSX, and for complex logic store the JSX in a variable above the return.

4. Leaving class and style strings as in HTML

class="card" triggers the development warning "Invalid DOM property `class`. Did you mean `className`?". style="color: red" is an outright error; write an object instead: style={{ color: "red" }}.

Best practices

Best practices

  • When an expression inside braces grows long, move it into a well-named variable above the return, such as const statusText = ....
  • Avoid nesting ternaries; with more than two outcomes, use if/else to set a variable instead.
  • When converting a large block of HTML, use an HTML-to-JSX converter or editor extension, then review the result.

Mini challenge

Mini challenge: a product badge

Write a ProductBadge component for an online shop. Show a product object's data through JSX expressions, and change the className, colour and text depending on whether it is in stock.

  • Show the product name in an <h3> with toUpperCase()
  • Show the price with two decimals using toFixed(2)
  • Use ternaries on inStock to choose the className, the style color and "In stock" or "Sold out"
  • Show the tags array with join(" / ") and include one JSX comment
ProductBadge.jsx
function ProductBadge() {
  const product = { name: "Wireless Mouse", price: 12.5, inStock: false };
  const tags = ["usb", "office"];

  return (
    <div className={/* TODO: "badge" or "badge badge--muted" */ "badge"}>
      {/* TODO: upper-case name in an <h3> */}
      {/* TODO: price with two decimals, e.g. "Price: 12.50 USD" */}
      {/* TODO: <p> with style color green/gray and In stock / Sold out */}
      {/* TODO: "Tags: usb / office" in a <small> */}
    </div>
  );
}

export default ProductBadge;

Expected: Because inStock is false, the div gets class "badge badge--muted" and shows "WIRELESS MOUSE", "Price: 12.50 USD", a gray "Sold out" and "Tags: usb / office".

Show hint

The style prop needs double braces: style={{ color: product.inStock ? "green" : "gray" }}. className accepts a ternary inside braces too.

Show solution
ProductBadge.jsx
function ProductBadge() {
  const product = { name: "Wireless Mouse", price: 12.5, inStock: false };
  const tags = ["usb", "office"];

  return (
    <div className={product.inStock ? "badge" : "badge badge--muted"}>
      <h3>{product.name.toUpperCase()}</h3>
      <p>Price: {product.price.toFixed(2)} USD</p>
      <p style={{ color: product.inStock ? "green" : "gray" }}>
        {product.inStock ? "In stock" : "Sold out"}
      </p>
      {/* tags are joined into one string */}
      <small>Tags: {tags.join(" / ")}</small>
    </div>
  );
}

export default ProductBadge;

Quick quiz 1 / 3

With const count = 0;, what does <p>{count && <b>New</b>}</p> show on the page?

Quick quiz 2 / 3

Which attribute links a <label> to an input in JSX?

Quick quiz 3 / 3

Which JSX correctly sets a paragraph's font size to 18px?

What to remember

  • JSX compiles to jsx("tag", props) calls that return { type, props } element objects.
  • Braces take expressions only; put if and for statements above the return.
  • One root (or a fragment), every tag closed, className and htmlFor, camelCase attributes and style objects.
  • false, null and undefined render nothing, 0 does render, and plain objects cannot be children.

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

What is JSX? | Thuta Learning