> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/preactjs/preact/llms.txt
> Use this file to discover all available pages before exploring further.

# Fragments

> Return multiple elements from a component without adding extra DOM nodes

Fragments let you group a list of children without adding extra nodes to the DOM. They're useful when you need to return multiple elements from a component but don't want to wrap them in a container element.

## Why Use Fragments?

Without fragments, you'd need to wrap multiple elements in a container:

```jsx theme={null}
// Without fragments - adds unnecessary div
function Component() {
  return (
    <div>
      <h1>Title</h1>
      <p>Paragraph</p>
    </div>
  );
}
```

This extra `<div>` can cause issues with:

* CSS layouts (flexbox, grid)
* Table structures
* List semantics
* Extra DOM nodes affecting performance

## Using Fragments

<Tabs>
  <Tab title="JSX Syntax (Recommended)">
    The most common way to use fragments is with the short syntax `<>...</>`:

    ```jsx theme={null}
    function Component() {
      return (
        <>
          <h1>Title</h1>
          <p>Paragraph</p>
        </>
      );
    }
    ```

    This renders the children without any wrapper element in the DOM.
  </Tab>

  <Tab title="Explicit Fragment">
    You can also use the explicit `Fragment` component:

    ```jsx theme={null}
    import { Fragment } from 'preact';

    function Component() {
      return (
        <Fragment>
          <h1>Title</h1>
          <p>Paragraph</p>
        </Fragment>
      );
    }
    ```

    Use this syntax when you need to add a key (see Keyed Fragments below).
  </Tab>
</Tabs>

## How Fragments Work

The `Fragment` component is implemented simply in `src/create-element.js`:

```javascript theme={null}
// From src/create-element.js:77-79
export function Fragment(props) {
  return props.children;
}
```

It just returns its children directly, without wrapping them. During diffing, Preact handles fragments specially to avoid creating wrapper DOM nodes.

Reference: `src/create-element.js:77-79`

## Common Use Cases

<CodeGroup>
  ```jsx Table Rows theme={null}
  function TableRows({ items }) {
    return (
      <>
        {items.map(item => (
          <tr key={item.id}>
            <td>{item.name}</td>
            <td>{item.value}</td>
          </tr>
        ))}
      </>
    );
  }

  function Table({ items }) {
    return (
      <table>
        <tbody>
          <TableRows items={items} />
        </tbody>
      </table>
    );
  }
  ```

  ```jsx List Items theme={null}
  function ListItems({ items }) {
    return (
      <>
        {items.map(item => (
          <li key={item.id}>{item.text}</li>
        ))}
      </>
    );
  }

  function List({ items }) {
    return (
      <ul>
        <ListItems items={items} />
      </ul>
    );
  }
  ```

  ```jsx Definition Lists theme={null}
  function DefinitionPair({ term, definition }) {
    return (
      <>
        <dt>{term}</dt>
        <dd>{definition}</dd>
      </>
    );
  }

  function Glossary({ entries }) {
    return (
      <dl>
        {entries.map(entry => (
          <DefinitionPair 
            key={entry.id}
            term={entry.term}
            definition={entry.definition}
          />
        ))}
      </dl>
    );
  }
  ```

  ```jsx Conditional Rendering theme={null}
  function UserInfo({ user, showDetails }) {
    return (
      <div className="user-card">
        <h2>{user.name}</h2>
        {showDetails && (
          <>
            <p>Email: {user.email}</p>
            <p>Phone: {user.phone}</p>
            <p>Location: {user.location}</p>
          </>
        )}
      </div>
    );
  }
  ```
</CodeGroup>

## Keyed Fragments

When rendering a list of fragments, you need to provide a `key` prop. The short syntax `<>` doesn't support keys, so use the explicit `Fragment` component:

<Steps>
  ### Basic Keyed Fragment

  ```jsx theme={null}
  import { Fragment } from 'preact';

  function Blog({ posts }) {
    return (
      <div>
        {posts.map(post => (
          <Fragment key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.excerpt}</p>
            <hr />
          </Fragment>
        ))}
      </div>
    );
  }
  ```

  ### Two-Column Layout

  ```jsx theme={null}
  import { Fragment } from 'preact';

  function TwoColumnList({ items }) {
    return (
      <div className="two-columns">
        {items.map(item => (
          <Fragment key={item.id}>
            <div className="column-a">{item.title}</div>
            <div className="column-b">{item.content}</div>
          </Fragment>
        ))}
      </div>
    );
  }
  ```

  ### Complex Table Structure

  ```jsx theme={null}
  import { Fragment } from 'preact';

  function ExpandableRow({ row, isExpanded }) {
    return (
      <Fragment key={row.id}>
        <tr>
          <td>{row.name}</td>
          <td>{row.value}</td>
        </tr>
        {isExpanded && (
          <tr>
            <td colSpan={2}>
              <div className="details">{row.details}</div>
            </td>
          </tr>
        )}
      </Fragment>
    );
  }
  ```
</Steps>

<Warning>
  When mapping over fragments, always use `<Fragment key={...}>` instead of `<>`.
</Warning>

## Fragments vs. Arrays

You might wonder: why use fragments when you can return an array?

<Tabs>
  <Tab title="With Fragments (Recommended)">
    ```jsx theme={null}
    function Component() {
      return (
        <>
          <h1>Title</h1>
          <p>Content</p>
        </>
      );
    }
    ```

    **Advantages:**

    * More readable JSX syntax
    * No need for keys on static elements
    * Consistent with React
  </Tab>

  <Tab title="With Arrays">
    ```jsx theme={null}
    function Component() {
      return [
        <h1 key="title">Title</h1>,
        <p key="content">Content</p>
      ];
    }
    ```

    **Disadvantages:**

    * Less readable
    * Requires keys even for static elements
    * Easy to forget keys
  </Tab>
</Tabs>

## Practical Examples

<CodeGroup>
  ```jsx Form Fields theme={null}
  function FormField({ label, name, type = 'text', error }) {
    return (
      <>
        <label htmlFor={name}>{label}</label>
        <input id={name} name={name} type={type} />
        {error && <span className="error">{error}</span>}
      </>
    );
  }

  function Form() {
    return (
      <form>
        <FormField label="Username" name="username" />
        <FormField label="Password" name="password" type="password" />
        <button type="submit">Login</button>
      </form>
    );
  }
  ```

  ```jsx Modal Content theme={null}
  function ModalContent({ title, children, onClose }) {
    return (
      <>
        <header className="modal-header">
          <h2>{title}</h2>
          <button onClick={onClose}>×</button>
        </header>
        <div className="modal-body">
          {children}
        </div>
        <footer className="modal-footer">
          <button onClick={onClose}>Close</button>
        </footer>
      </>
    );
  }
  ```

  ```jsx Responsive Menu theme={null}
  function MenuItem({ href, label, icon }) {
    return (
      <>
        <a href={href} className="mobile-menu-item">
          {icon && <span className="icon">{icon}</span>}
          <span>{label}</span>
        </a>
        <a href={href} className="desktop-menu-item">
          {label}
        </a>
      </>
    );
  }

  function Menu({ items }) {
    return (
      <nav>
        {items.map(item => (
          <MenuItem 
            key={item.href}
            href={item.href}
            label={item.label}
            icon={item.icon}
          />
        ))}
      </nav>
    );
  }
  ```

  ```jsx Card Grid theme={null}
  import { Fragment } from 'preact';

  function CardRow({ cards }) {
    return cards.map(card => (
      <Fragment key={card.id}>
        <div className="card-image">
          <img src={card.image} alt={card.title} />
        </div>
        <div className="card-title">{card.title}</div>
        <div className="card-description">{card.description}</div>
      </Fragment>
    ));
  }

  function CardGrid({ cards }) {
    return (
      <div className="grid">
        <CardRow cards={cards} />
      </div>
    );
  }
  ```
</CodeGroup>

## Best Practices

<Steps>
  ### Use the short syntax when possible

  ```jsx theme={null}
  // Good: Short syntax for simple cases
  function Component() {
    return (
      <>
        <Header />
        <Main />
      </>
    );
  }

  // Only use explicit Fragment when you need keys
  import { Fragment } from 'preact';

  function Component({ items }) {
    return items.map(item => (
      <Fragment key={item.id}>
        <div>{item.title}</div>
        <div>{item.content}</div>
      </Fragment>
    ));
  }
  ```

  ### Don't wrap unnecessarily

  ```jsx theme={null}
  // Bad: Unnecessary wrapper
  function Component() {
    return (
      <div>
        <Header />
      </div>
    );
  }

  // Good: Return directly if single element
  function Component() {
    return <Header />;
  }

  // Good: Use fragment for multiple elements
  function Component() {
    return (
      <>
        <Header />
        <Main />
      </>
    );
  }
  ```

  ### Consider semantic HTML

  Sometimes a wrapper element is better for semantics or styling:

  ```jsx theme={null}
  // Not always best: Fragment in navigation
  function Nav({ items }) {
    return (
      <nav>
        {items.map(item => (
          <>
            <a href={item.href}>{item.label}</a>
            <span> | </span>
          </>
        ))}
      </nav>
    );
  }

  // Better: Use a list for semantics
  function Nav({ items }) {
    return (
      <nav>
        <ul>
          {items.map(item => (
            <li key={item.href}>
              <a href={item.href}>{item.label}</a>
            </li>
          ))}
        </ul>
      </nav>
    );
  }
  ```

  ### Always add keys to mapped fragments

  ```jsx theme={null}
  import { Fragment } from 'preact';

  // Bad: Missing keys
  function Component({ items }) {
    return items.map(item => (
      <>
        <h3>{item.title}</h3>
        <p>{item.text}</p>
      </>
    ));
  }

  // Good: Keyed fragments
  function Component({ items }) {
    return items.map(item => (
      <Fragment key={item.id}>
        <h3>{item.title}</h3>
        <p>{item.text}</p>
      </Fragment>
    ));
  }
  ```
</Steps>

## Performance Considerations

Fragments have no performance overhead - they don't create extra DOM nodes or components. They're just a syntax feature that tells Preact to render children directly.

```jsx theme={null}
// These are functionally equivalent in the DOM:

// With wrapper (creates <div> in DOM)
<div>
  <h1>Title</h1>
  <p>Text</p>
</div>

// With fragment (no wrapper in DOM)
<>
  <h1>Title</h1>
  <p>Text</p>
</>

// Resulting DOM for both:
<h1>Title</h1>
<p>Text</p>
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Server-Side Rendering" icon="server" href="/guides/server-side-rendering">
    Render Preact components on the server
  </Card>

  <Card title="TypeScript" icon="code" href="/guides/typescript">
    Use Preact with TypeScript for type safety
  </Card>
</CardGroup>
