Getting styled-components to work with Next v14 and App router
Unanswered
Turkish Angora posted this in #help-forum
Turkish AngoraOP
Hello, I am currently trying to get styled-components working in my Next v14 project.
I followed the docs (https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components)
and I am getting the error:
Here is my code:
I followed the docs (https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components)
and I am getting the error:
createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.Here is my code:
app/page.tsximport styled from "styled-components";
const Test = styled.h1`
color: red;
`;
export default function Home() {
return <Test>Hello world</Test>;
}app/layout.tsximport type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import StyledComponentsRegistry from "@lib/registry";
const inter = Inter({ subsets: ["latin"] });
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
<StyledComponentsRegistry>{children}</StyledComponentsRegistry>
</body>
</html>
);
}app/lib/registry.tsx"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>;
}