Skip to the workspace
Pebellslearn by building
Components and JSX  ›  Lesson

JSX — Markup Inside JavaScript

JSX 14 minJSX is HTML-like syntax inside JavaScript where curly braces hold any expression, attributes use camelCase names, and a component returns one root element.

react / JSX — Markup Inside JavaScript

Explore each scene at your own pace.

01 · The rule

The rule

JSX — Markup Inside JavaScript

JSX looks like HTML, so it is tempting to paste HTML straight in. Most of it works, and the parts that do not work fail in small, annoying ways. Learn the handful of differences once and you will stop tripping over them.

The rule

Braces open JavaScript; everything else is strict, camelCase HTML.

Braces let you drop any JavaScript expression into markup: a variable, a calculation, a function call.

const book = { title: 'The Hobbit', pages: 310, cover: '/hobbit.jpg' };

function BookCard() {
  return (
    <article className="book">
      <h2>{book.title}</h2>
      <p>{book.pages} pages, about {Math.round(book.pages / 30)} days</p>
      <img src={book.cover} alt={book.title} />
    </article>
  );
}

Only expressions fit in braces. An if statement or a for loop does not; you will meet the expression forms (? :, &&, map) in the Rendering section.

Strict means:

  • One root element per return. Wrap siblings in a parent or an empty fragment, <>...</>, which adds nothing to the page.
  • Every tag is closed: <img />, <br />, <input />.

camelCase HTML means attributes use JavaScript property names:

  • class → className, for → htmlFor
  • onclick → onClick, tabindex → tabIndex
  • style takes an object: style={{ fontSize: 18 }}. The outer braces open JavaScript; the inner braces are the object. Numbers mean pixels for most size properties.

Two exceptions keep their dashes: aria-* and data-* attributes, such as aria-label.

Comments inside markup go in braces too: {/* like this */}.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.