Next 13버전 styled-components 사용

봉희·2023년 9월 8일
1

next

목록 보기
2/4

Next 13버전에서부터 기존 pages 디렉토리 방식을 사용하지 않고, app 디렉토리에 _app과 _document는 사용하지 않아서 새로운 방식으로 적용을 해야했다..

// lib/rootRegistry.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>
  );
}
  • lib폴더를 만들고 rootRegistry나 registry를 만든 후 styled-compoentns에 대한 코드를 추가
// app/layout.tsx

import "./globals.css";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import RootStyleRegistry from "@/lib/RootStyleRegistry";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="ko">
      <body>
        <RootStyleRegistry>{children}</RootStyleRegistry>
      </body>
    </html>
  );
}
// next.config.js

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

module.exports = nextConfig;

이와 같이 작성 하면 next13버전에서 styled-compoentns를 사용할 수 있다.

profile
3년 차 웹 풀스택 개발자 | 더 나은 사용자 경험을 만드는 개발자

0개의 댓글