From de147a219f9358c5d81006bb34f59b090f36cc32 Mon Sep 17 00:00:00 2001 From: busybox11 Date: Sat, 24 Aug 2024 01:43:09 +0200 Subject: [PATCH] fix: Use NextJS recommended config for styled-components --- next.config.mjs | 10 +++++---- src/app/layout.tsx | 5 +++-- src/lib/styled-components-registry.tsx | 29 ++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 src/lib/styled-components-registry.tsx diff --git a/next.config.mjs b/next.config.mjs index 48f03d4..431d026 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -3,17 +3,19 @@ const nextConfig = { images: { remotePatterns: [ { - protocol: 'https', - hostname: 'raw.githubusercontent.com', + protocol: "https", + hostname: "raw.githubusercontent.com", }, ], }, experimental: { serverActions: { // edit: updated to new key. Was previously `allowedForwardedHosts` - allowedOrigins: ['localhost:3000', 'get-zen.vercel.app'], + allowedOrigins: ["localhost:3000", "get-zen.vercel.app"], }, - + }, + compiler: { + styledComponents: true, }, }; diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 3de6cf4..971e56e 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,7 +1,8 @@ import type { Metadata } from "next"; import { Inter } from "next/font/google"; import "./globals.css"; -import { ThemeProvider } from "@/components/theme-provider" +import { ThemeProvider } from "@/components/theme-provider"; +import StyledComponentsRegistry from "@/lib/styled-components-registry"; const inter = Inter({ subsets: ["latin"] }); @@ -25,7 +26,7 @@ export default function RootLayout({ enableSystem disableTransitionOnChange > - {children} + {children} diff --git a/src/lib/styled-components-registry.tsx b/src/lib/styled-components-registry.tsx new file mode 100644 index 0000000..fa12293 --- /dev/null +++ b/src/lib/styled-components-registry.tsx @@ -0,0 +1,29 @@ +"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 ( + + {children} + + ); +}