프내기

[styled-components]Global style, Theme 적용 오류 본문

Trouble Shooting

[styled-components]Global style, Theme 적용 오류

봄나물소년 2023. 11. 21. 03:26

Global style과 ThemeProvider을 이용하여 전역 css와 theme을 적용하고싶었다.

처음에 root layout 파일(layout.ts)에 <GlobalStyle/> 태그를 두어 적용하려했지만

에러가 떴다.

 

"그거 쓰려면 맨 위에 "use client" 써줄래?" 라고 한다.

```
<ThemeProvider theme={theme}>
  <GlobalStyle>
    {children}
  </GlobalStyle>
</ThemeProvider>
    
```

그래서 Global style과 ThemeProvider 태그를 지워보았더니 에러가 사라지며 화면이 잘 나온다.

이유가 궁금하여 스오플을 찾아보았더니 이 에러를 똑같이 경험한 사람의 글이 나온다.

https://stackoverflow.com/questions/77164068/how-to-add-theme-provider-in-next-js-app

 

how to add theme provider in next.js app?

i want to add themeprovider to my app so i can easily change between dark and light mode this how my layout.tsx looks like: import "./globals.css"; import "@/styles/nav.css"; im...

stackoverflow.com

 

요약하면 ThemeProvider client side에서 실행된다고 한다.

즉, client component인 것이다.

그러니 당연히 "use client"를 써야한다.

고맙게도 해결책까지 제시가 되어있다.

바로 layout.ts 안에 하나의 컴포넌트를 새로 만들어 children을 감싸고 그 안에서 children을 props로 받는다.

그 다음 새 컴포넌트 안에서 부모에서 받은 children을 themeprovider로 감싸주는 것이다.

+) 추가로 global style태그도 추가한다.

 

// app/layout.js

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
          <ThemeClient>
            <div className="screen">
              qweqwe
              {children}
            </div>
          </ThemeClient>
      </body>
    </html>
  )
}

 

// app/ThemeClient.ts

"use client"

import { ThemeProvider } from "styled-components";
import theme from '@/styles/theme';
import GlobalStyle from "../styles/GlobalStyles";

export default function ThemeClient({ children }: {
  children: React.ReactNode
}) {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle>
        {children}
      </GlobalStyle>
    </ThemeProvider>
  )
}

 

에러가 사라졌다.

하지만 뒤이어 나오는 또 다른 에러

 

"global style한테 자식 jsx가 주어졌네? 얘는 자식 못 가짐요ㅠ"

아하!

 

// app/ThemeClient.ts

"use client"

import { ThemeProvider } from "styled-components";
import theme from '@/styles/theme';
import GlobalStyle from "../styles/GlobalStyles";

export default function ThemeClient({ children }: {
  children: React.ReactNode
}) {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle/>
        {children}
    </ThemeProvider>
  )
}

 

children을 감싼 glbalStyle 태그를 옆으로 뺴주니 에러가 모두 사라졌다.