feat: bring back <Head> component (#3249)
This PR brings back the `<Head>` component from Fresh 1.x . The implementation is much cleaner than back then and also works client-side now too.
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
---
|
||||
description: Modify the document head in Fresh
|
||||
---
|
||||
|
||||
The
|
||||
[`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/head)-element
|
||||
is a crucial element in HTML to set metadata for a page. It allows you to:
|
||||
|
||||
- Set the document title with `<title>`
|
||||
- Specify page metadata with `<meta>`
|
||||
- Link to resources like stylesheets with `<link>`
|
||||
- Include JavaScript code with `<script>`
|
||||
|
||||
> [info]: The outer HTML structure including `<head>` is typically created
|
||||
> inside `_app.tsx`.
|
||||
|
||||
## Passing metadata from `ctx.state`
|
||||
|
||||
For simple scenarios passing metadata along from a handler or a middleware by
|
||||
writing to `ctx.state` is often sufficient.
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
import { define } from "../util.ts";
|
||||
|
||||
export default define.page((ctx) => {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>{ctx.state.title ?? "Welcome!"}</title>
|
||||
</head>
|
||||
<body>
|
||||
<ctx.Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## Using the `<Head>`-component
|
||||
|
||||
For more complex scenarios, or to set page metadata from islands, Fresh ships
|
||||
with the `<Head>`-component.
|
||||
|
||||
```tsx routes/about.tsx
|
||||
import { Head } from "fresh/runtime";
|
||||
|
||||
export default define.page((ctx) => {
|
||||
return (
|
||||
<div>
|
||||
<Head>
|
||||
<title>About me</title>
|
||||
</Head>
|
||||
<h1>About me</h1>
|
||||
<p>I like Fresh!</p>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
### Avoiding duplicate tags
|
||||
|
||||
You might end up with duplicate tags, when multiple `<Head />` components are
|
||||
rendered on the same page. Fresh will employ the following strategies to find
|
||||
the matching element:
|
||||
|
||||
1. For `<title>` elements Fresh will set `document.title` directly
|
||||
2. Check if an element with the same `key` exists
|
||||
3. Check if an element with the same `id` attribute
|
||||
4. Only for `<meta>` elements: Check if there is a `<meta>` element with the
|
||||
same `name` attribute
|
||||
5. No matching element was found, Fresh will create a new one and append it to
|
||||
`<head>`
|
||||
|
||||
> [info]: The `<title>`-tag is automatically deduplicated, even without a `key`
|
||||
> prop.
|
||||
@@ -147,53 +147,6 @@ accordingly.
|
||||
}
|
||||
```
|
||||
|
||||
## Removal of `<Head>` component
|
||||
|
||||
The `<Head>` component was used in Fresh 1.x to add additional tags to the
|
||||
`<head>` portion of an HTML document from anywhere on the page. This feature was
|
||||
removed in preparation and due to performance concerns as it required a complex
|
||||
machinery in the background to work.
|
||||
|
||||
Instead, passing head-related data is best done via `ctx.state`, which can be
|
||||
easily set through the [define helper](/docs/canary/advanced/define).
|
||||
|
||||
```tsx
|
||||
// utils.ts
|
||||
export interface State {
|
||||
title?: string;
|
||||
}
|
||||
export const define = createDefine<State>();
|
||||
|
||||
// routes/about.tsx
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export default define.page(function AboutPage(ctx) {
|
||||
// Set a route specific data in a handler
|
||||
ctx.state.title = "About Me";
|
||||
return (
|
||||
<div>
|
||||
<h1>About Me</h1>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
// Render that in _app.tsx
|
||||
export default define.page(function App({ Component, state }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
{state.title ? <title>{state.title}</title> : null}
|
||||
</head>
|
||||
<body>
|
||||
<Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## Update deployment settings
|
||||
|
||||
Fresh 2 requires assets to be build during deployment instead of building them
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
---
|
||||
description: |
|
||||
Modify <head> content by passing state between AppWrapper/Layout and routes.
|
||||
---
|
||||
|
||||
It's a common requirement for specific pages to need changes to content inside
|
||||
the `<head>` tag.
|
||||
|
||||
- Setting the document title using `<title>`
|
||||
- Specifying page metadata using `<meta>`
|
||||
- Linking to resources like stylesheets using `<link>`
|
||||
- Including third-party JavaScript code using `<script>`
|
||||
|
||||
## App Wrapper with State
|
||||
|
||||
The recommended way to modify content in `<head>` is to use an app wrapper in
|
||||
combination with `Context.state`.
|
||||
|
||||
### 1. State
|
||||
|
||||
The first step can be to define the possible state available on `Context`. In
|
||||
this example, the `State` is very general to allow very flexible usage.
|
||||
|
||||
```ts util.ts
|
||||
import { createDefine } from "fresh";
|
||||
import type { JSX } from "preact";
|
||||
|
||||
export interface State {
|
||||
title?: string;
|
||||
metas?: JSX.IntrinsicElements["meta"][];
|
||||
links?: JSX.IntrinsicElements["link"][];
|
||||
scripts?: JSX.IntrinsicElements["script"][];
|
||||
}
|
||||
|
||||
export const define = createDefine<State>();
|
||||
```
|
||||
|
||||
### 2. App wrapper
|
||||
|
||||
After defining the State, create the App Wrapper to render the HTML with the
|
||||
provided State.
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
import { define } from "../util.ts";
|
||||
|
||||
export default define.page(function AppWrapper(ctx) {
|
||||
const { title, links, metas, scripts } = ctx.state;
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>{title ? `${title} | My App` : "My App"}</title>
|
||||
|
||||
{metas?.map((attrs, i) => <meta key={i} {...attrs} />)}
|
||||
{links?.map((attrs, i) => <link key={i} {...attrs} />)}
|
||||
{scripts?.map((attrs, i) => <script key={i} {...attrs} />)}
|
||||
</head>
|
||||
<body>
|
||||
<ctx.Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Route data
|
||||
|
||||
Then it's up to each route to update the State with `<head>` data you want to
|
||||
add for that route. For this to work correctly, the State must be set in a route
|
||||
handler. Inside the route Component is too late, as it runs after the App
|
||||
Wrapper.
|
||||
|
||||
```tsx routes/index.tsx
|
||||
import { page } from "fresh";
|
||||
import { asset } from "fresh/runtime";
|
||||
import { define } from "../util.ts";
|
||||
|
||||
const hero = asset("/hero.webp");
|
||||
|
||||
export const handler = define.handlers(({ state: s }) => {
|
||||
s.title = "Home";
|
||||
s.metas = [{ name: "description", content: "Welcome to the homepage!" }];
|
||||
s.links = [
|
||||
{ rel: "stylesheet", href: asset("/home.css"), type: "text/css" },
|
||||
{ rel: "preload", href: hero, as: "image", type: "image/webp" },
|
||||
];
|
||||
s.scripts = [{ src: "https://example.com/script.js" }];
|
||||
|
||||
return page();
|
||||
});
|
||||
|
||||
export default define.page(function Home() {
|
||||
return <img class="hero" src={hero} alt="Hero Image" />;
|
||||
});
|
||||
```
|
||||
|
||||
If it's very common to add e.g. `title`/`description` to many pages, it can help
|
||||
a lot to [create State helpers](#state-helper-utility). This can reduce
|
||||
boilerplate for creating handlers that set metadata on `ctx.state`.
|
||||
|
||||
## Using Multiple Layouts
|
||||
|
||||
Layouts can be used to use shared `<head>` content for groups of pages. The base
|
||||
HTML layout can be used as a shared component.
|
||||
|
||||
```tsx components/AppWrapper.tsx
|
||||
import type { RenderableProps } from "preact";
|
||||
import type { State } from "../util.ts";
|
||||
|
||||
export function AppWrapper(props: RenderableProps<State>) {
|
||||
const { title, styles, children } = props;
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
|
||||
<title>{title ? `${title} | My App` : "My App"}</title>
|
||||
|
||||
{styles?.map((url, i) => <link key={i} rel="stylesheet" href={url} />)}
|
||||
</head>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The component above can then be used by multiple layouts that needs to share the
|
||||
same `<head>` content.
|
||||
|
||||
```tsx routes/docs/_layout.tsx
|
||||
import { asset } from "fresh/runtime";
|
||||
import { define } from "../util.ts";
|
||||
import { AppWrapper } from "../component/AppWrapper.tsx";
|
||||
|
||||
export default define.page(function DocsLayout() {
|
||||
return (
|
||||
<AppWrapper title="Docs" styles={[asset("/docs.css")]}>
|
||||
<h1>Welcome to Docs!</h1>
|
||||
</AppWrapper>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
```tsx routes/blog/_layout.tsx
|
||||
import { asset } from "fresh/runtime";
|
||||
import { define } from "../util.ts";
|
||||
import { AppWrapper } from "../component/AppWrapper.tsx";
|
||||
|
||||
export default define.page(function BlogLayout() {
|
||||
return (
|
||||
<AppWrapper title="Blog" styles={[asset("/blog.css")]}>
|
||||
<h1>My blog</h1>
|
||||
</AppWrapper>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## State helper utility
|
||||
|
||||
There's many ways to use abstractions or structure your code when using Fresh.
|
||||
If many pages needs to set metadata, but otherwise does not require a handler,
|
||||
it can be handy to create a utility for this.
|
||||
|
||||
```ts util.ts
|
||||
export interface State {
|
||||
title?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export const define = createDefine<State>();
|
||||
|
||||
export const pageMetadataHandler = (title: string, description?: string) =>
|
||||
define.handlers((ctx) => {
|
||||
ctx.state.title = title;
|
||||
ctx.state.description = description;
|
||||
});
|
||||
```
|
||||
|
||||
This helper can reduce boilerplate when creating many routes where each route
|
||||
needs unique metadata.
|
||||
|
||||
```tsx routes/blog.tsx
|
||||
import { pageMetadataHandler } from "../utils.ts";
|
||||
|
||||
export const handlers = pageMetadataHandler("Blog", "Read about ...");
|
||||
```
|
||||
|
||||
```tsx routes/about.tsx
|
||||
import { pageMetadataHandler } from "../utils.ts";
|
||||
|
||||
export const handlers = pageMetadataHandler("About", "Our company ...");
|
||||
```
|
||||
+1
-1
@@ -54,6 +54,7 @@ const toc: RawTableOfContents = {
|
||||
["forms", "Forms", "link:canary"],
|
||||
["define", "Define Helpers", "link:canary"],
|
||||
["environment-variables", "Environment Variables", "link:canary"],
|
||||
["head", "Modifying <head>", "link:canary"],
|
||||
],
|
||||
},
|
||||
deployment: {
|
||||
@@ -85,7 +86,6 @@ const toc: RawTableOfContents = {
|
||||
pages: [
|
||||
["migration-guide", "Migration Guide", "link:canary"],
|
||||
["daisyui", "daisyUI", "link:canary"],
|
||||
["modifying-the-head", "Modifying the <head>", "link:canary"],
|
||||
["creating-a-crud-api", "Creating a CRUD API", "link:latest"],
|
||||
["markdown", "Rendering Markdown", "link:canary"],
|
||||
["rendering-raw-html", "Rendering raw HTML", "link:canary"],
|
||||
|
||||
Reference in New Issue
Block a user