How to integrate Nextjs + styled-components with material-ui
This solution works fine for server-side, for client side you also need to change the injection order, as documented here: https://material-ui.com/customization/css-in-js/#css-injection-order
To make this work with next.js, you need to change the asignation of the jss constant like this:
const jss = create({
...jssPreset(),
insertionPoint: process.browser
? window.document.getElementById('jss-insertion-point')
: null
})
Give this a try
_document.js
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components'
import { ServerStyleSheets } from '@material-ui/styles';
import theme from '../src/theme';
class MyDocument extends Document {
static async getInitialProps (ctx) {
const styledComponentsSheet = new ServerStyleSheet()
const materialSheets = new ServerStyleSheets()
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () => originalRenderPage({
enhanceApp: App => props => styledComponentsSheet.collectStyles(materialSheets.collect(<App {...props} />))
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<React.Fragment>
{initialProps.styles}
{materialSheets.getStyleElement()}
{styledComponentsSheet.getStyleElement()}
</React.Fragment>
)
}
} finally {
styledComponentsSheet.seal()
}
}
render() {
return (
<html lang="en" dir="ltr">
<Head>
<meta charSet="utf-8" />
{/* Use minimum-scale=1 to enable GPU rasterization */}
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/>
{/* PWA primary color */}
<meta
name="theme-color"
content={theme.palette.primary.main}
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
export default MyDocument;
.babelrc
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
For update check https://github.com/nblthree/nextjs-with-material-ui-and-styled-components
here is my _document.js
file looks like:
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();
}
}
}
and below find my .babelrc
file:
{
"presets": ["next/babel"],
"plugins": [
["styled-components", { "ssr": true }]
]
}