Skip to content

Commit

Permalink
Simplify styled-components example (#5631)
Browse files Browse the repository at this point in the history
- use `enhanceApp` so that styled-components used in _app.js are server rendered
- call parent getInitialProps, fixes #5629
- return `styles`, making the render() method obsolete.

cc @mxstbr @probablyup
  • Loading branch information
timneutkens committed Nov 8, 2018
1 parent a0137d4 commit ed2c379
Showing 1 changed file with 9 additions and 18 deletions.
27 changes: 9 additions & 18 deletions examples/with-styled-components/pages/_document.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
import Document, { Head, Main, NextScript } from 'next/document'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
static getInitialProps ({ renderPage }) {
static async getInitialProps (ctx) {
const sheet = new ServerStyleSheet()
const page = renderPage(App => props => sheet.collectStyles(<App {...props} />))
const styleTags = sheet.getStyleElement()
return { ...page, styleTags }
}

render () {
return (
<html>
<Head>
{this.props.styleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
const originalRenderPage = ctx.renderPage
ctx.renderPage = () => originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
})

const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps, styles: [...initialProps.styles, ...sheet.getStyleElement()] }
}
}

3 comments on commit ed2c379

@ek
Copy link

@ek ek commented on ed2c379 Dec 12, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@chhuang
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timneutkens how do I add my own <html> and <body> with this setup?

@timneutkens
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like normal, add a render() method holding the tags from the documentation

Please sign in to comment.