~/hackweb.dev
JSX Syntax
Quiz
...

JSX Syntax

beginner · updated Tue Sep 08 2026Contribute

Write UI with JSX — JavaScript XML that looks like HTML.

JSX Syntax

JSX is a syntax extension for JavaScript that looks like HTML. React uses it to describe what the UI should look like.

Embedding Expressions

Wrap any JavaScript expression in curly braces {}:

const name = "Alice";
const element = <h1>Hello, {name}!</h1>;

You can use any expression — variables, function calls, ternaries, math.

Self-Closing Tags

Every tag must be closed. HTML-style self-closing works:

const img = <img src="photo.jpg" alt="Photo" />;
const input = <input type="text" />;

Forgetting the / is a common syntax error.

Fragments

Return multiple elements without an extra wrapper:

function List() {
  return (
    <>
      <li>One</li>
      <li>Two</li>
    </>
  );
}

<> is shorthand for <React.Fragment>. No extra DOM nodes are created.

JSX is Not HTML

JSX uses camelCase for attributes:

// HTML                    JSX
class="box"         →     className="box"
for="email"         →     htmlFor="email"
onclick={handler}   →     onClick={handler}
tabindex="0"        →     tabIndex="0"

Style values are objects, not strings:

<div style={{ color: "red", fontSize: "16px" }}>Red text</div>

Returning JSX

A component must return a single root element:

function Card() {
  return (
    <div>
      <h2>Title</h2>
      <p>Body</p>
    </div>
  );
}

Use a fragment if you don’t need a wrapper div.

Best Practices

  1. Use fragments — Avoid unnecessary divs in the DOM
  2. Keep JSX readable — Break into multiple lines for complex elements
  3. Use className and htmlFor — Not class and for
  4. Self-close empty tags<img />, <input />, <br />

Common Mistakes

  1. Forgetting return parentheses — Multi-line JSX needs () after return
  2. Using class instead of className — JSX uses camelCase
  3. Returning multiple root elements — Wrap in a fragment or div
  4. Using quotes for dynamic values — Use {} for JavaScript expressions