Search code examples
next.jsstyled-components

I want to render styled-components by server-side in Next.13. How i do?


the component is being rendered before styling at a certain time

I want to render the styled-components on the server side


Solution

  • The answer in documentation: https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components

    create lib/registry.tsx with this code

    'use client';
     
    import React, { useState } from 'react';
    import { useServerInsertedHTML } from 'next/navigation';
    import { ServerStyleSheet, StyleSheetManager } from 'styled-components';
     
    export default function StyledComponentsRegistry({
      children,
    }: {
      children: React.ReactNode;
    }) {
      // Only create stylesheet once with lazy initial state
      // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
      const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet());
     
      useServerInsertedHTML(() => {
        const styles = styledComponentsStyleSheet.getStyleElement();
        styledComponentsStyleSheet.instance.clearTag();
        return <>{styles}</>;
      });
     
      if (typeof window !== 'undefined') return <>{children}</>;
     
      return (
        <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
          {children}
        </StyleSheetManager>
      );
    }
    

    and wrap the child in global layout (app/layout.tsx)

    import StyledComponentsRegistry from './lib/registry';
     
    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode;
    }) {
      return (
        <html>
          <body>
            <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
          </body>
        </html>
      );
    }