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
Q. Next.js에서 styled-component 글로벌 스타일 적용하려면?
https://sooncoding.tistory.com/196
'프론트엔드 > Next.js' 카테고리의 다른 글
[Next.js] Next.js 환경에서 MUI integration 방법 + MUI 전역 스타일링 방법 (0) | 2024.12.03 |
---|---|
[Next.js] "use client"는 CSR 방식과 동일할까? (1) | 2024.12.02 |
[Next.js] Next.js에서 SVG를 컴포넌트처럼 사용하는 방법 (0) | 2024.12.01 |
Next.js + Supabase 프로젝트에서 NEXT_PUBLIC 환경 변수에 anon 키를 저장했을 경우에 보안 위협성 (0) | 2024.11.26 |
[Next.js] 서버 컴포넌트 VS 클라이언트 컴포넌트 (0) | 2024.08.14 |