Qwik City - Layout
When implementing routes, different routes usually share a common header, footer, and menu system. We call the common parts layout.
The developer could extract all of these into <Header>
, <Footer>
, and <Menu>
components, but that is error-prone and repetitive. 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> |
| - main | |
| - 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>
- home.tsx # https://example.com/home
- about.tsx # https://example.com/about
Note: Alternatively src/_layout.tsx
can be src/_layout/index.tsx
for the same outcome.
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>main</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/home.tsx
export default component$(() => {
return <>Home</>;
});
// File: src/routes/about.tsx
export default component$(() => {
return <>About</>;
});