Next.js Discord

Discord Forum

Getting styled-components to work with Next v14 and App router

Unanswered
Turkish Angora posted this in #help-forum
Open in Discord
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:
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.tsx
import styled from "styled-components";

const Test = styled.h1`
    color: red;
`;

export default function Home() {
    return <Test>Hello world</Test>;
}


app/layout.tsx
import 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>;
}

0 Replies