프론트엔드/Next.js

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

순코딩 2024. 12. 17. 10:24
Next.js + styled-components 글로벌 스타일 적용
1) 글로벌 스타일 생성
src / styles / GlobalStyles.tsx
"use client";

import { createGlobalStyle } from "styled-components";

const GlobalStyles = createGlobalStyle`
  :root {
  /* 기본 색상 */
  --main-color: #2ECC71;
  
  /* 서브 색상 (보조 색상) */
  --secondary-color: #FFFFFF;
  --third-color: #FFA726; 
  }
  
  /* Anchor 태그 기본 스타일 */
  a {
    text-decoration: none;
    color: inherit;
  }

  /* 버튼 스타일 */
  button {
    cursor: pointer;
    border: none;
    background: none;
  }
`;

export default GlobalStyles;

 

2) 루트 레이아웃에서 children 상단에 GlobalStyles.tsx 컴포넌트 호출(랩핑 X, 닫힌 태그(<GlobalStyles/>)로 호출 O)
src / app / layout.tsx
import GlobalStyles from "@/styles/GlobalStyles";
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>
          <GlobalStyles />
          {children}
        </StyledComponentsRegistry>
      </body>
    </html>
  );
}

 

3) 테스트 
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:var(--main-color);
  color:white;
  font-size:100px;
`

 

끝.