What is the method for implementing Styled-components in NextJs13 while utilizing SSR?
add a comment
To implement Styled-components in Next.js 13 while utilizing SSR, follow these steps:
npm install --save styled-components babel-plugin-styled-components
module.exports = {
presets: ["next/babel"],
plugins: [["styled-components", { ssr: true }]],
};
import Document, { Html, Head, Main, NextScript } 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() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
import { createGlobalStyle, ThemeProvider } from "styled-components";
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
`;
const theme = {
colors: {
primary: "#0070f3",
},
};
function MyApp({ Component, pageProps }) {
return (
<>
<GlobalStyle />
<ThemeProvider theme={theme}>
<Component {...pageProps} />
</ThemeProvider>
</>
);
}
export default MyApp;
import styled from "styled-components";
const Button = styled.button`
background-color: ${(props) => props.theme.colors.primary};
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 4px;
`;
export default function Home() {
return <Button>Hello World!</Button>;
}
Now, when you run your Next.js app, your styled-components will be rendered on the server and hydrated on the client.
Asked: 2022-07-22 11:00:00 +0000
Seen: 7 times
Last updated: Jan 25 '23