문제 해결
문제 해결 (Troubleshooting)
이 문서는 Material UI v4에서 v5로 마이그레이션할 때 마주치는 알려진 문제와 흔한 문제들을 다뤄요.
출처: 문서
본문
Material UI v5 마이그레이션
- 시작하기
- 깨지는 변경 사항 1부: 스타일과 테마
- 깨지는 변경 사항 2부: 컴포넌트
- JSS에서 마이그레이션하기
- 문제 해결 👈 당신은 여기
v5로 마이그레이션한 후 스타일이 깨짐 (Styles broken after migrating to v5)
마이그레이션 과정의 모든 단계를 완료했는데도 컴포넌트 스타일이 깨지는 데는 두 가지 이유가 있어요.
먼저 Style 라이브러리 절에 나온 대로 StyledEngineProvider를 올바르게 설정했는지 확인해 보세요.
애플리케이션 최상단에서 StyledEngineProvider를 이미 사용하고 있는데도 스타일이 여전히 깨진다면, 애플리케이션에 여전히 @material-ui/core가 남아 있을 수 있어요.
이것은 앱의 다른 의존성이 여전히 Material UI v4에 의존하고 있기 때문일 수 있어요.
확인하려면 npm ls @material-ui/core(또는 yarn why @material-ui/core)를 실행해 보세요. 프로젝트에 그런 의존성이 있다면 아래와 비슷한 목록이 보일 거예요.
$ npm ls @material-ui/core
project@0.1.0 /path/to/project
└─┬ @mui/x-data-grid@4.0.0
└── @material-ui/core@4.12.3
위 출력은 @material-ui/core가 @mui/x-data-grid의 의존성이라는 것을 나타내요.
이 특정 예시에서는 @mui/x-data-grid 버전을 v5로 올려서 대신 @mui/material에 의존하도록 해야 해요.
Storybook과 Emotion
프로젝트가 Storybook v6.x를 사용한다면 .storybook/main.js 웹팩 설정을 최신 버전의 Emotion을 사용하도록 업데이트해야 해요.
// .storybook/main.js
const path = require('path');
const toPath = (filePath) => path.join(process.cwd(), filePath);
module.exports = {
webpackFinal: async (config) => {
return {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
'@emotion/core': toPath('node_modules/@emotion/react'),
'emotion-theming': toPath('node_modules/@emotion/react'),
},
},
};
},
};
다음으로 .storybook/preview.js를 업데이트해서 Storybook의 Docs 탭이 빈 페이지를 표시하지 않도록 해요.
// .storybook/preview.js
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { ThemeProvider as Emotion10ThemeProvider } from 'emotion-theming';
const defaultTheme = createTheme(); // or your custom theme
const withThemeProvider = (Story, context) => {
return (
<Emotion10ThemeProvider theme={defaultTheme}>
<ThemeProvider theme={defaultTheme}>
<Story {...context} />
</ThemeProvider>
</Emotion10ThemeProvider>
);
};
export const decorators = [withThemeProvider];
// ...other storybook exports
:::info
이 솔루션은 다음 버전에서 테스트됐어요.
{
"@storybook/react": "6.3.8",
"@storybook/addon-docs": "6.3.8",
"@emotion/react": "11.4.1",
"@emotion/styled": "11.3.0",
"@mui/material": "5.0.2"
}
이것은 임시 해결책(workaround)이며, 다른 버전을 사용한다면 상황에 맞지 않을 수 있다는 점을 알아두세요.
자세한 내용은 이 GitHub 이슈들을 확인해 보세요.
- https://github.com/storybookjs/storybook/issues/16099
- https://github.com/mui/material-ui/issues/24282#issuecomment-796755133
:::
null의 scrollTop 속성을 읽을 수 없음 (Cannot read property scrollTop of null)
이 오류는 Fade, Grow, Slide, Zoom 컴포넌트에서 DOM 노드가 없어서 발생해요.
커스텀 컴포넌트의 경우 자식이 ref를 DOM으로 전달(forward)하는지 확인하세요.
// Ex. 1-1 ❌ This will cause an error because the Fragment is not a DOM node:
<Fade in>
<React.Fragment>
<CustomComponent />
</React.Fragment>
</Fade>
// Ex. 1-2 ✅ Add a DOM node such as this div:
<Fade in>
<div>
<CustomComponent />
</div>
</Fade>
// Ex. 2-1 ❌ This will cause an error because `CustomComponent` does not forward `ref` to the DOM:
function CustomComponent() {
return <div>...</div>;
}
<Fade in>
<CustomComponent />
</Fade>;
// Ex. 2-2 ✅ Add `React.forwardRef` to forward `ref` to the DOM:
const CustomComponent = React.forwardRef(function CustomComponent(props, ref) {
return (
<div ref={ref}>
...
</div>
)
})
<Fade in>
<CustomComponent />
</Fade>
자세한 내용은 GitHub의 이 이슈를 확인해 보세요.
[Types] 'DefaultTheme' 타입에 "palette", "spacing" 속성이 없음
이 오류는 makeStyles가 이제 @mui/styles 패키지에서 내보내지는데, 이 패키지가 core 패키지의 Theme에 대해 알지 못하기 때문에 발생해요.
이를 고치려면 @mui/styles의 DefaultTheme(빈 객체)를 core의 Theme으로 보강(augment)해야 해요.
모듈 보강에 대해 더 자세히 알아보려면 공식 TypeScript 문서를 읽어보세요.
TypeScript
테마 파일에 이 스니펫을 추가해요.
// it could be your App.tsx file or theme file that is included in your tsconfig.json
import { Theme } from '@mui/material/styles';
declare module '@mui/styles/defaultTheme' {
// eslint-disable-next-line @typescript-eslint/no-empty-interface (remove this line if you don't have the rule enabled)
interface DefaultTheme extends Theme {}
}
JavaScript
VS Code처럼 d.ts 파일에서 타입을 추론할 수 있는 IDE를 사용한다면, src 폴더에 index.d.ts를 만들고 다음 코드 줄을 추가해요.
// index.d.ts
declare module '@mui/private-theming' {
import type { Theme } from '@mui/material/styles';
interface DefaultTheme extends Theme {}
}
[Jest] SyntaxError: Unexpected token 'export'
@mui/material/colors/red는 v1.0.0부터 private로 간주돼요. 이 오류를 고치려면 import를 교체해야 해요. 자세한 내용은 이 GitHub 이슈를 참고하세요.
프로젝트의 모든 import를 고치려면 이 codemod를 사용하는 걸 권장해요.
npx @mui/codemod@latest v5.0.0/optimal-imports <path>
이렇게 수동으로 고칠 수도 있어요.
-import red from '@mui/material/colors/red';
+import { red } from '@mui/material/colors';
makeStyles - TypeError: Cannot read property 'drawer' of undefined
이 오류는 다음 예시처럼 <ThemeProvider>의 범위 밖에서 useStyles 또는 withStyles를 호출할 때 발생해요.
import * as React from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import makeStyles from '@mui/styles/makeStyles';
import Card from '@mui/material/Card';
import CssBaseline from '@mui/material/CssBaseline';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
backgroundColor: theme.palette.primary.main,
color: theme.palette.common.white,
},
}));
const theme = createTheme();
function App() {
const classes = useStyles(); // ❌ called outside of ThemeProvider
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Card className={classes.root}>...</Card>
</ThemeProvider>
);
}
export default App;
useStyles를 다른 컴포넌트 안으로 옮겨서 <ThemeProvider> 아래에서 호출되도록 하면 고칠 수 있어요.
// ...imports
function AppContent(props) {
const classes = useStyles(); // ✅ This is safe because it is called inside ThemeProvider
return <Card className={classes.root}>...</Card>;
}
function App(props) {
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<AppContent {...props} />
</ThemeProvider>
);
}
export default App;
TypeError: Cannot read properties of undefined (reading 'pxToRem')
이 오류는 빈 테마에 접근하려고 해서 발생해요.
다음 문제들을 해결했는지 확인하세요.
styled는 (독립형@mui/system을 사용하지 않는다면)@mui/material/styles에서만 import해야 해요.
import { styled } from '@mui/material/styles';
useStyles는<ThemeProvider>밖에서 호출할 수 없어요. 이 문제를 고치려면 이 절의 지침을 따르세요.
자세한 내용은 이 GitHub 이슈를 참고하세요.
여전히 문제가 있나요? (Still having problems?)
여기에 다루지 않은 문제를 만났다면 [Migration] 문제 요약 형식의 제목으로 GitHub 이슈를 만들어 주세요.