Working with styled-components in Next.js.

Ahmer Patel
1 min readSep 7, 2021

wondering why you cannot see your styling when migrating from a react app to next.js ? don’t worry I have got you covered.

Just follow these two steps :

  1. Add a custom .babelrc file
  • npm i babel-plugin-styled-components (a must for server-side rendering) applications which uses styled-compnents
  • add this code to your “.babelrc” file, make sure you keep “ssr ”as true value
{
"presets": [
"next/babel"
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}
  1. Add a custom _document.js file

We will be extending the <Document /> and injecting the server side rendered styles into the <head>.

This is exactly how your ._document.js file should like , which will override the existing default <Document /> .

import Document, { Head,Html, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet();

const page = renderPage((App) => (props) =>
sheet.collectStyles(<App {...props} />),
);

const styleTags = sheet.getStyleElement();

return { ...page, styleTags };
}

render() {
return (
<Html>
<Head>
<title>My page</title>
{this.props.styleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

This should solve the error , and your styled-components should work exactly how you wanted it to work.

--

--