Next.js에서 styled-component 사용시
초기로딩시 스타일링 되지 않은 html 문서가 보임
이를 해결하기
1._document.tsx 커스텀
https://nextjs.org/docs/advanced-features/custom-document
import Document, {DocumentContext} from 'next/document'
import {ServerStyleSheet} from 'styled-components'
class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
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()}
</>
]
}
} catch (error) {
throw error
} finally {
sheet.seal()
}
}
}
export default MyDocument
Advanced Features: Custom `Document` | Next.js
Extend the default document markup added by Next.js.
nextjs.org
2. next.config.js 추가하기 (nextjs 12.1버전부터는!)
compiler: { styledComponents: true },
출처 : https://been.tistory.com/m/56
Next.js styled-component 적용 문제에 대해(_document.tsx)
Nextjs에서 styled-components를 사용하면 서버상에서 html을 불러온 뒤, hydrate과정에서 js를 입혀 스타일이 적용된다. 이때 초기 페이지 로딩시 사용자가 보게 되는 화면은, 스타일링이 전혀 적용되지않
been.tistory.com
https://styled-components.com/docs/advanced#nextjs
styled-components: Advanced Usage
Theming, refs, Security, Existing CSS, Tagged Template Literals, Server-Side Rendering and Style Objects
styled-components.com