styled-components-website icon indicating copy to clipboard operation
styled-components-website copied to clipboard

Need a FAQ page added for this

Open quantizor opened this issue 2 years ago • 3 comments

If anyone needs a step by step on how to make styled-components work with Next.js 13 (app router) without any "delay bugs" using client-side rendering, here it is:

Step 1: add the following to your next.config.js file

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  compiler: {
    styledComponents: true,
  },
}

module.exports = nextConfig

Step 2: create the registry.tsx file with the following 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>
  )
}

Step 3: add the 'use client' directive to your layout.tsx file and wrap all the children components on your layout with the StyledComponentsRegistry component.

I've made a tutorial if anyone needs further help: https://www.youtube.com/watch?v=3tgrPm2aKog

Originally posted by @lucasmelz in https://github.com/styled-components/styled-components/issues/3856#issuecomment-1597789823

quantizor avatar Jun 20 '23 12:06 quantizor