반응형
styled-components를 next에서 사용하면 문제점이 발생한다.
바로 CSS-in-JS로 스타일링을 하면 스타일이 적용되지 않은 html 코드가 먼저 렌더링되는 문제가 발생하게 된다.
NextJS는 이에 대한 해결책을 제시한다. html 파일에 CSS-in-JS 형식으로 작성된 스타일 요소들을 주입시켜서 스타일이 뒤늦게 적용되는 문제를 해결할 수 있다.
👉 NextJS 공식문서 - Customizing 'renderPage'
// pages/_document.tsx
import Document, { DocumentContext, DocumentInitialProps } from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: [
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>,
],
};
} finally {
sheet.seal();
}
}
}
또 다른 문제점이 있다면 server와 client에서 생성되는 class값이 달라 충돌하는 문제점이 있다.
이때 👉 babel-plugin-styled-components를 설치하고 .babelrc 파일을 설정하도록 하면 된다.
{
"presets": ["next/babel"],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": true
}
]
]
}
반응형
'nodebird' 카테고리의 다른 글
넥스트에서의 에디터... (1) | 2024.01.25 |
---|---|
blog만드는중... (0) | 2024.01.21 |
블로그도 만들어 봅시다. (0) | 2024.01.16 |
Mysql을 다뤄봅시다 (0) | 2024.01.03 |
Node기초 (0) | 2024.01.03 |