Fondu

Layouts

View as Markdown

A layout is the part of the page that stays the same from one page to the next: a header, a sidebar, a footer. It stays mounted while navigations move between the pages it wraps, so its state (a scroll position, an open menu) is kept.

_layout.tsx

A _layout.tsx in a directory of app/routes/ wraps every page below it. Its default export is a component that renders the page as children:

// app/routes/_layout.tsx: around every page
import type { ReactNode } from 'react'

import '../styles/app.css'

export default function Layout({ children }: { children: ReactNode }) {
  return (
    <>
      <header>…</header>
      <main>{children}</main>
    </>
  )
}

The root layout is around every page, the error page too: the place to import the app's CSS. Layouts nest with the directories, outermost first:

app/routes/
├─ _layout.tsx           # around every page
├─ index.tsx
└─ docs/
   ├─ _layout.tsx        # around the docs pages, inside the one above
   ├─ intro.mdx
   └─ routes.mdx

/docs/intro is rendered inside _layout.tsx, then docs/_layout.tsx. Pages written in MDX get their layouts the same way. Read the page and its props in a layout with usePage() (fondu/client).

Different layouts for different parts

A (group) directory adds no segment to the URLs: its pages share a layout without sharing a path.

app/routes/
├─ _layout.tsx           # the styles, around everything
├─ (marketing)/
│  ├─ _layout.tsx        # the site's header and footer
│  ├─ index.tsx          # /
│  └─ legal/
│     ├─ _layout.tsx     # a narrow column, inside the marketing layout
│     ├─ terms.tsx       # /legal/terms
│     └─ privacy.tsx
└─ admin/
   ├─ _layout.tsx        # the dashboard's sidebar, not the site's header
   └─ users.tsx          # /admin/users

A part that should not sit inside a layout goes in a directory beside it: admin/ is not in (marketing)/.

The pattern for most apps: the root _layout.tsx is the shell (the CSS, providers), and the site's chrome (header, footer) is in (site)/_layout.tsx. A page that should render alone, such as a sign-in or a print view, sits outside (site)/:

app/routes/
├─ _layout.tsx           # the shell: CSS, providers
├─ (site)/
│  ├─ _layout.tsx        # the header and footer
│  ├─ index.tsx          # /
│  └─ about.tsx          # /about
└─ sign-in.tsx           # /sign-in, without the header and footer

Code-split with their pages

A layout is in the JavaScript of its pages only: a visitor of the home page doesn't download the docs' sidebar. The client loads a page's _layout.tsx files with it, found by the page's route file.

Files that are not routes

A file in app/routes/ whose name starts with _, or that is in a directory whose name does, is not a route: it has no URL, and it is not in the generated types. Besides _layout.tsx, a component used by the pages of one directory can live there too, as _toc.tsx or _parts/toc.tsx. Tests (*.test.*, *.spec.*) are not routes either.

Last updated