Layout

When implementing routes, different routes usually share a common header, footer, and menu system. We call the common parts a layout.

The developer could extract all of these into <Header>, <Footer>, and <Menu> components and manually add them to each page component, but that is repetitive and error-prone. Instead, we can use layouts to automatically reuse common parts.

Example

Let's say we would like our site to look like this:

┌───────────────────────────────────────────────────┐
│ Header                                            │
├─────────┬─────────────────────────────────────────┤
│ Menu    │ <ROUTE_SPECIFIC_CONTENT>                │
│ - home  │                                         │
│ - about │                                         │
│         │                                         │
├─────────┴─────────────────────────────────────────┤
│ Footer                                            │
└───────────────────────────────────────────────────┘

We can define the above with these files.

src/
├── components/
│   ├── header.tsx         # Header component implementation
│   ├── footer.tsx         # Footer component implementation
│   └── menu.tsx           # Menu component implementation
└── routes/
    ├── layout.tsx         # Layout implementation using: <Header>, <Footer>, and <Menu>
    ├── about/
    │   └── index.tsx      # https://example.com/about
    └── index.tsx          # https://example.com

Component implementations

// File: src/components/header.tsx
export default component$(() => {
  return <>Header</>;
});
// File: src/components/footer.tsx
export default component$(() => {
  return <>Footer</>;
});
// File: src/components/menu.tsx
export default component$(() => {
  return (
    <ul>
      <li>home</li>
      <li>about</li>
    </ul>
  );
});
// File: src/routes/layout.tsx
export default component$(() => {
  return (
    <>
      <Header />
      <Menu />
      <Slot/> {/* <== This is where the route will be inserted */}
      <Footer />
    </>
  );
});
// File: src/routes/index.tsx
export default component$(() => {
  return <>Home</>;
});
// File: src/routes/about/index.tsx
export default component$(() => {
  return <>About</>;
});
Made with ❤️ by