Open utterances-bot opened 2 years ago
항상 잘 보고 있습니다! mui를 styled-components와 같이 사용하고자 하는데 _document를 어떻게 수정해야 할까요?!
@KimGnab 글 제작중이긴 하지만 급하신것 같아서 코드랑 대충 설명만 적어두겠습니다!
import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
import { ServerStyleSheets } from "@mui/styles";
export default class MyDocument extends Document {
render() {
return (
<Html>
<Main />
<NextScript />
</Html>
);
}
}
MyDocument.getInitialProps = async ctx => {
const sheet = new ServerStyleSheet();
const materialSheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props =>
sheet.collectStyles(materialSheets.collect(<App {...props} />))
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
)
};
} finally {
sheet.seal();
}
};
sheet.collectStyles(materialSheets.collect(<App {...props} />))
이것 처럼 mui collect를 styled로 감싸주면 됩니다!
코드 감사합니다! 다음 글도 기대하고 있겠습니다😎
안녕하세요 경환님!
몇 가지 궁금한 점이 생겨서 댓글 남깁니다. mui 5에서는 이모션 라이브러리를 기반으로 css가 빌드되기 때문에, 4버전과는 달리 추가적인 패키지가 필요한 것으로 확인했습니다. 이 글에서도 관련 라이브러리를 설치하고 있더라구요.
mui 공식 문서에서는 next.js앱에 mui5를 적용하도록 _document.js 파일을 커스텀할때 다음과 같은 방식을 따릅니다.
const cache = createEmotionCache(); const { extractCriticalToChunks } = createEmotionServer(cache);
캐치를 선언하고, 선언한 캐치를 이모션 서버에 등록해서 서버사이드를 지원하고 있는데요 글쓴이님의 방식과는 조금 달라보입니다.
공교롭게도 저 또한 팀에서 진행하는 프로젝트의 레거시 몇 군데에서 스타일드 컴포넌트가 사용되고 있는 상태인데요, mui를 위처럼 적용하고 있을때 스타일드 컴포넌트를 이 다음글과 같이 적용시킬 수 있는지 궁금합니다!
공식문서에서 제안하는 프로젝트 예제 : https://github.com/mui/material-ui/blob/master/examples/nextjs/pages/_document.js
next.js에서 material-ui 사용하기 (typescript) | 기억보다 기록을
next.js에서 material-ui 사용하기, react, next, seo, ssr, dynamic meta content, getInitialProps, mui
https://kyounghwan01.github.io/blog/React/next/mui/