Ask Your Question
0

What is the method for implementing Styled-components in NextJs13 while utilizing SSR?

asked 2022-07-22 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-01-25 01:00:00 +0000

scrum gravatar image

To implement Styled-components in Next.js 13 while utilizing SSR, follow these steps:

  1. Install styled-components and babel-plugin-styled-components.
npm install --save styled-components babel-plugin-styled-components
  1. Create a babel.config.js file at the root of your project and add the following code:
module.exports = {
  presets: ["next/babel"],
  plugins: [["styled-components", { ssr: true }]],
};
  1. Create a _document.js file in your pages folder and add the following code:
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>
    );
  }
}
  1. Create a _app.js file in your pages folder and add the following code:
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;
  1. Finally, you can use styled-components in your components like so:
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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-22 11:00:00 +0000

Seen: 7 times

Last updated: Jan 25 '23