Server side rendering Styled-Components with NextJS
- Make sure you have these packages in package.json:
{
"dependencies": {
"next": "latest",
"react": "^16.8.0",
"react-dom": "^16.8.0",
"styled-components": "latest"
},
"devDependencies": {
"babel-plugin-styled-components": "latest",
}
- And in .babelrc
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
- Finally, let’s take a look at _document.js: this is where the magic happens.
Styled-components creates an instance of ServerStyleSheet This stylesheet retrieves any styles found in all the components inside our
<App />
. This then gets passed into our Html template later on.
import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
render() {
//render here!
}
}