프론트엔드/Next.js

[Next.js] Next.js + Styled-components 적용하기

순코딩 2024. 11. 30. 14:54
1. Next.js + styled-components 세팅
1) next.config.ts 파일 수정
{projectName} / next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  compiler: {
    styledComponents: true,
  },
};

export default nextConfig;

 

2) registry.tsx 파일 생성
src / utils / 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>
  )
}

 

3) 루트 레이아웃에서 children을 registry.tsx로 랩핑
src / app / layout.tsx
import StyledComponentsRegistry from "@/utils/registry";
import type { Metadata } from "next";

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

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  );
}

 

4) 테스트
src / app / page.tsx
"use client"

import styled from "styled-components";

export default function Home() {
  return <Container>Hello World</Container>;
}

const Container = styled.div`
  background-color:blue;
  color:white;
  font-size:100px;
`

 

참고자료

https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components

 

Styling: CSS-in-JS | Next.js

Use CSS-in-JS libraries with Next.js

nextjs.org

 

 

Q. Next.js에서 styled-component 글로벌 스타일 적용하려면?

https://sooncoding.tistory.com/196

 

[Next.js] Next.js에서 styled-components 글로벌 스타일 적용 방법

Next.js + styled-components 글로벌 스타일 적용1) 글로벌 스타일 생성src / styles / GlobalStyles.tsx"use client";import { createGlobalStyle } from "styled-components";const GlobalStyles = createGlobalStyle` :root { /* 기본 색상 */ --main-

sooncoding.tistory.com