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</>;
});