1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Show warning if there is a title in _document.js's Head (#5160)

* show warning if there is a title in _document.js Head

* dont loop through children in production

* only 1 loop through this.props.children 💪

* also raise warning in test env

* check for null childs
This commit is contained in:
Luc 2018-09-28 00:24:12 +02:00 committed by Tim Neutkens
parent ad93ff4b3e
commit f8dfe026ec
2 changed files with 55 additions and 1 deletions

View file

@ -0,0 +1,43 @@
# `<title>` should not be used in _document.js's `<Head>`
#### Why This Error Occurred
Adding `<title>` in `pages/_document.js` will lead to unexpected results with `next/head` since `_document.js` is only rendered on the initial pre-render.
#### Possible Ways to Fix It
Set `<title>` in `pages/_app.js` instead :
```js
// pages/_app.js
import App, {Container} from 'next/app'
import Head from 'next/head'
import React from 'react'
export default class MyApp extends App {
static async getInitialProps ({ Component, router, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return {pageProps}
}
render () {
const {Component, pageProps} = this.props
return <Container>
<Head>
<title>My new cool app</title>
</Head>
<Component {...pageProps} />
</Container>
}
}
```
### Useful Links
- [The issue this was reported in: #4596](https://github.com/zeit/next.js/issues/4596)

View file

@ -104,6 +104,17 @@ export class Head extends Component {
const { page, pathname, buildId } = __NEXT_DATA__
const pagePathname = getPagePathname(pathname)
let children = this.props.children
// show a warning if Head contains <title> (only in development)
if (process.env.NODE_ENV !== 'production') {
children = React.Children.map(children, (child) => {
if (child && child.type === 'title') {
console.warn("Warning: <title> should not be used in _document.js's <Head>. https://err.sh/next.js/no-document-title")
}
return child
})
}
return <head {...this.props}>
{(head || []).map((h, i) => React.cloneElement(h, { key: h.key || i }))}
{page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}`} as='script' nonce={this.props.nonce} />}
@ -113,7 +124,7 @@ export class Head extends Component {
{this.getPreloadMainLinks()}
{this.getCssLinks()}
{styles || null}
{this.props.children}
{children}
</head>
}
}