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