Chapter 4 of 4

Fragments and Structure

Returning several elements, self-closing tags and the rules JSX enforces.

JSX has a few structural rules that trip people up early. They all come from the same place: JSX compiles to a function call, and a function call returns one value.

One root element

A component returns a single element. Two sibling elements at the top level are a syntax error.

// Error: adjacent JSX elements must be wrapped
function Row() {
  return (
    <td>Name</td>
    <td>Email</td>
  );
}

You could wrap them in a <div>, but that adds a node to the DOM that may break table or flex layouts. A fragment groups children without producing any element.

<>...</> is shorthand for <Fragment>...</Fragment>.
import { Fragment } from "react";

function Row() {
  return (
    <>
      <td>Name</td>
      <td>Email</td>
    </>
  );
}

// The long form, needed when you have to pass a key
function List({ entries }) {
  return entries.map((entry) => (
    <Fragment key={entry.id}>
      <dt>{entry.term}</dt>
      <dd>{entry.definition}</dd>
    </Fragment>
  ));
}

Every tag must close

HTML lets you leave some tags open. JSX does not: every element is either closed or self-closed.

<br />
<img src="/logo.png" alt="Logo" />
<input type="text" />
<div className="box"></div>

Comments and whitespace

Comments inside JSX go in braces. Whitespace between lines is collapsed, so use {" "} when you need a space React would otherwise drop.

<p>
  {/* This is a JSX comment */}
  <strong>Total</strong>{" "}
  <span>42</span>
</p>

Build a small profile card

Return a fragment containing an h3 with the name and a p with the role. Do not add a wrapper div.