rsnext/docs/api-reference/next/head.md
Yossi Spektor 23d71ff116
Any elements must be direct children of next/head (#11557)
It is any elements and not only meta or title because the children of next/head are generated in here: 8c899ee5e4/packages/next/next-server/lib/head.tsx (L139)
where React.cloneElement is called without the third parameter which is needed to clone the children as well (https://reactjs.org/docs/react-api.html#cloneelement).
2020-04-06 13:35:22 +02:00

71 lines
2 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
description: Add custom elements to the `head` of your page with the built-in Head component.
---
# next/head
<details>
<summary><b>Examples</b></summary>
<ul>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/head-elements">Head Elements</a></li>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/layout-component">Layout Component</a></li>
</ul>
</details>
We expose a built-in component for appending elements to the `head` of the page:
```jsx
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<p>Hello world!</p>
</div>
)
}
export default IndexPage
```
To avoid duplicate tags in your `head` you can use the `key` property, which will make sure the tag is only rendered once, as in the following example:
```jsx
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
<meta
name="viewport"
content="initial-scale=1.0, width=device-width"
key="viewport"
/>
</Head>
<Head>
<meta
name="viewport"
content="initial-scale=1.2, width=device-width"
key="viewport"
/>
</Head>
<p>Hello world!</p>
</div>
)
}
export default IndexPage
```
In this case only the second `<meta name="viewport" />` is rendered.
> The contents of `head` get cleared upon unmounting the component, so make sure each page completely defines what it needs in `head`, without making assumptions about what other pages added.
`title`, `meta` or any other elements (e.g.`script`) need to be contained as **direct** children of the `Head` element,
or wrapped into maximum one level of `<React.Fragment>`, otherwise the tags won't be correctly picked up on client-side navigations.