styled-components 는 컴포넌트가 실행이 될때 같이 그려주기 때문에 서버사이드 렌더링으로 불러오는 페이지에서는 css가 안 입혀져서 불러오는 문제가 생긴다. 그래서 styled-components 도 서버에서 같이 그려줘서 가져올 수 있게끔 어느정도 설정이 필요하다.
.babelrc 파일을 package.json파일과 같은 경로에다가 생성을 해 준다.
{
"presets": ["next/babel"],
"plugins": [["styled-components",
{ "ssr": true,"displayName": true }]]
}
해당 코드 추가해 주기.
import Document from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
// sheet을 사용해 정의된 모든 스타일을 수집
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
// Documents의 initial props
const initialProps = await Document.getInitialProps(ctx);
// props와 styles를 반환
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
}
이렇게 하면 스타일 적용이 잘 될것이다.