-
-
Notifications
You must be signed in to change notification settings - Fork 436
Open
Description
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 styled-components/styled-components#3856 (comment)
Metadata
Metadata
Assignees
Labels
No labels