styled components 스타일이 적용전에 렌더가 되는 문제 해결법
npx create-next-app [파일명]
yarn add styled-components
yarn add -D babel-plugin-styled-components
루트 파일에 .babelrc 파일 만들기
.babelrc
{
"presets": [
"next/babel"
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}
pages 폴더 아래에 _document.js 생성
import Document, { Head, Main, NextScript } from 'next/document';
// Import styled components ServerStyleSheet
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
// Step 1: Create an instance of ServerStyleSheet
const sheet = new ServerStyleSheet();
// Step 2: Retrieve styles from components in the page
const page = renderPage((App) => (props) =>
sheet.collectStyles(<App {...props} />),
);
// Step 3: Extract the styles as <style> tags
const styleTags = sheet.getStyleElement();
// Step 4: Pass styleTags as a prop
return { ...page, styleTags };
}
render() {
return (
<html>
<Head>
<title>My page</title>
{/* Step 5: Output the styles in the head */}
{this.props.styleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
참고
https://dev.to/aprietof/nextjs--styled-components-the-really-simple-guide----101c