v5의 깨지는 변경 사항 1부: 스타일과 테마
v5의 깨지는 변경 사항 1부: 스타일과 테마 (Breaking changes in v5, part one: styles and themes)
이 문서는 Material UI v5에서 도입된 깨지는 변경 사항과 v4에서 마이그레이션하는 방법을 설명하는 참고 가이드예요. 이 부분은 스타일링과 테마 관련 변경을 다뤄요.
출처: 문서
본문
Material UI v5 마이그레이션
- 시작하기
- 깨지는 변경 사항 1부: 스타일과 테마 👈 당신은 여기
- 깨지는 변경 사항 2부: 컴포넌트
- JSS에서 마이그레이션하기
- 문제 해결
깨지는 변경 사항, 1부 (Breaking changes, part one)
Material UI v5는 v4에서의 많은 깨지는 변경을 도입해요. 이 변경들 중 다수는 주요 마이그레이션 가이드에 설명된 codemods를 사용해 자동으로 해결할 수 있어요.
다음 문서는 v5의 스타일과 테마 관련 모든 깨지는 변경과 이를 해결하는 방법을 나열해요.
여기를 끝내면 마이그레이션 과정을 계속하기 위해 v5의 깨지는 변경 사항 2부: 컴포넌트로 이동하세요.
:::warning codemod가 처리하는 깨지는 변경은 화면 오른쪽 목차에서 ✅ 이모지로 표시돼요.
이미 주요 마이그레이션 가이드의 지침을 따르고 codemods를 실행했다면, 이 항목들에 대해 더 조치할 필요가 없어야 해요.
그 외 모든 변경은 수동으로 처리해야 해요. :::
테마 styleOverrides를 Emotion으로 마이그레이션하기 (Migrate theme styleOverrides to Emotion)
로컬 규칙 참조 리팩터링 (Refactor local rule references)
테마에 정의한 스타일 오버라이드가 부분적으로는 동작할 수 있지만, 중첩 요소가 스타일링되는 방식에는 중요한 차이가 있어요.
JSS에서 사용했던 $ 문법(로컬 규칙 참조)은 Emotion에서 동작하지 않아요. 그 선택자들을 유효한 클래스 선택자로 교체해야 해요.
상태 클래스 이름 교체 (Replace state class names)
const theme = createTheme({
components: {
MuiOutlinedInput: {
styleOverrides: {
root: {
- '&$focused': {
+ '&.Mui-focused': {
borderWidth: 1,
}
}
}
}
}
});
중첩 클래스 선택자를 전역 클래스 이름으로 교체 (Replace nested classes selectors with global class names)
const theme = createTheme({
components: {
MuiOutlinedInput: {
styleOverrides: {
root: {
- '& $notchedOutline': {
+ '& .MuiOutlinedInput-notchedOutline': {
borderWidth: 1,
}
}
}
}
}
});
:::info
각 컴포넌트에 대해 해당 컴포넌트의 모든 중첩 클래스를 담은 [component]Classes 상수를 내보내요.
클래스를 하드코딩하는 대신 이것에 의존할 수 있어요. :::
+import { outlinedInputClasses } from '@mui/material/OutlinedInput';
const theme = createTheme({
components: {
MuiOutlinedInput: {
styleOverrides: {
root: {
- '& $notchedOutline': {
+ [`& .${outlinedInputClasses.notchedOutline}`]: {
borderWidth: 1,
}
}
}
}
}
});
사용 가능한 전역 상태 클래스 이름 목록 전체를 살펴보세요.
공백·쉼표 구분 값의 대체 문법 리팩터링 (Refactor alternative syntax for space- and comma-separated values)
JSS가 공백·쉼표 구분 값에 대해 지원하는 배열 기반 대체 문법은 Emotion에서 지원되지 않아요.
배열 기반 값을 문자열 기반 값으로 교체 (Replace array-based values with string-based values)
이전
const theme = createTheme({
overrides: {
MuiBox: {
root: {
background: [
['url(image1.png)', 'no-repeat', 'top'],
['url(image2.png)', 'no-repeat', 'center'],
'!important',
],
},
},
},
});
이후
const theme = createTheme({
components: {
MuiBox: {
styleOverrides: {
root: {
background:
'url(image1.png) no-repeat top, url(image2.png) no-repeat center !important',
},
},
},
},
});
숫자 값에는 단위를 적절히 추가하는 것을 잊지 마세요.
이전
const theme = createTheme({
overrides: {
MuiOutlinedInput: {
root: {
padding: [[5, 8, 6]],
},
},
},
});
이후
const theme = createTheme({
components: {
MuiOutlinedInput: {
styleOverrides: {
root: {
padding: '5px 8px 6px',
},
},
},
},
});
ref
ref를 전달하지 않는 클래스 컴포넌트 리팩터링 (Refactor non-ref-forwarding class components)
component prop 또는 직접적인 children에서 ref를 전달하지 않는 클래스 컴포넌트의 지원이 중단됐어요.
unstable_createStrictModeTheme를 사용하고 있었거나 React.StrictMode에서 findDOMNode 관련 경고를 보지 못했다면 더 조치할 필요가 없어요.
그렇지 않으면 Composition 가이드의 Caveat with refs 절을 확인해서 마이그레이션하는 방법을 알아보세요. 이 변경은 component prop을 사용하거나 children이 요소여야 하는 컴포넌트(예: <MenuList><CustomMenuItem /></MenuList>)에 children을 전달하는 거의 모든 컴포넌트에 영향을 줘요.
ref 타입 특수성 수정 (Fix ref type specificity)
일부 컴포넌트에서는 ref를 전달할 때 타입 오류가 발생할 수 있어요. 오류를 피하려면 특정 요소 타입을 사용해야 해요. 예를 들어 Card는 ref 타입이 HTMLDivElement일 것을 기대하고, ListItem은 ref 타입이 HTMLLIElement일 것을 기대해요.
예시가 있어요.
import * as React from 'react';
import Card from '@mui/material/Card';
import ListItem from '@mui/material/ListItem';
export default function SpecificRefType() {
- const cardRef = React.useRef<HTMLElement>(null);
+ const cardRef = React.useRef<HTMLDivElement>(null);
- const listItemRef = React.useRef<HTMLElement>(null);
+ const listItemRef = React.useRef<HTMLLIElement>(null);
return (
<div>
<Card ref={cardRef}></Card>
<ListItem ref={listItemRef}></ListItem>
</div>
);
}
각 컴포넌트가 기대하는 특정 요소 타입은 다음과 같아요.
@mui/material
- Accordion -
HTMLDivElement - Alert -
HTMLDivElement - Avatar -
HTMLDivElement - ButtonGroup -
HTMLDivElement - Card -
HTMLDivElement - Dialog -
HTMLDivElement - ImageList -
HTMLUListElement - List -
HTMLUListElement - Tab -
HTMLDivElement - Tabs -
HTMLDivElement - ToggleButton -
HTMLButtonElement
@mui/lab
- Timeline -
HTMLUListElement
스타일 라이브러리 (Style library)
✅ CSS 주입 순서 조정
v5에서 기본으로 사용하는 스타일 라이브러리는 Emotion이에요.
Material UI 컴포넌트의 스타일 오버라이드에 JSS를 사용하고 있었다면—예를 들어 makeStyles로 만든 것들—CSS 주입 순서를 신경 써야 해요. JSS <style> 요소는 Emotion <style> 요소 뒤에 <head>에 주입되어야 해요.
이렇게 하려면 컴포넌트 트리 최상단에 injectFirst 옵션을 가진 StyledEngineProvider가 있어야 해요. 아래와 같이요.
import * as React from 'react';
import { StyledEngineProvider } from '@mui/material/styles';
export default function GlobalCssPriority() {
return (
{/* Inject Emotion before JSS */}
<StyledEngineProvider injectFirst>
{/* Your component tree. Now you can override Material UI's styles. */}
</StyledEngineProvider>
);
}
✅ createCache에 prepend 추가
커스텀 캐시가 있고 Emotion으로 앱을 스타일링하고 있다면, Material UI가 제공하는 캐시를 덮어쓸 거예요.
주입 순서를 바로잡으려면 아래처럼 createCache에 prepend 옵션을 추가해요.
import * as React from 'react';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
const cache = createCache({
key: 'css',
+ prepend: true,
});
export default function PlainCssPriority() {
return (
<CacheProvider value={cache}>
{/* Your component tree. Now you can override Material UI's styles. */}
</CacheProvider>
);
}
:::warning
styled-components를 사용하고 커스텀 target을 가진 StyleSheetManager가 있다면, 그 target이 HTML <head>의 첫 번째 요소인지 확인하세요.
이를 어떻게 하는지 보려면 @mui/styled-engine-sc 패키지의 StyledEngineProvider 구현을 살펴보세요.
:::
테마 구조 (Theme structure)
✅ adaptV4Theme 헬퍼 추가
v5에서 테마의 구조가 바뀌었어요. 그 모양을 업데이트해야 해요. 더 매끄러운 전환을 위해 adaptV4Theme 헬퍼로 일부 테마 변경을 새 테마 구조로 반복적으로 업그레이드할 수 있어요.
-import { createMuiTheme } from '@mui/material/styles';
+import { createTheme, adaptV4Theme } from '@mui/material/styles';
-const theme = createMuiTheme({
+const theme = createTheme(adaptV4Theme({
// v4 theme
-});
+}));
:::warning
이 어댑터는 createTheme()의 입력 인자만 처리해요. 테마 생성 후 테마의 모양을 수정한다면 구조를 수동으로 마이그레이션해야 해요.
:::
어댑터가 지원하는 변경은 다음과 같아요.
gutters 제거 (Remove gutters)
"gutters" 추상화는 자주 사용되어 가치가 있음을 입증하지 못했어요.
-theme.mixins.gutters(),
+paddingLeft: theme.spacing(2),
+paddingRight: theme.spacing(2),
+[theme.breakpoints.up('sm')]: {
+ paddingLeft: theme.spacing(3),
+ paddingRight: theme.spacing(3),
+},
✅ px 접미사 제거
theme.spacing은 이제 기본적으로 px 단위의 단일 값을 반환해요. 이 변경은 styled-components와 Emotion과의 통합을 개선해요.
이전:
theme.spacing(2) => 16
이후:
theme.spacing(2) => '16px'
✅ theme.palette.type 이름 변경
theme.palette.type 키는 theme.palette.mode로 이름이 바뀌었어요. 이 기능을 설명할 때 보통 쓰는 "dark mode" 용어를 더 잘 따르기 위해서예요.
import { createTheme } from '@mui/material/styles';
-const theme = createTheme({ palette: { type: 'dark' } }),
+const theme = createTheme({ palette: { mode: 'dark' } }),
기본 theme.palette.info 색상 변경
기본 theme.palette.info 색상이 라이트/다크 모드 모두에서 AA 접근성 표준 대비비를 통과하도록 바뀌었어요.
info = {
- main: cyan[500],
+ main: lightBlue[700], // lightBlue[400] in "dark" mode
- light: cyan[300],
+ light: lightBlue[500], // lightBlue[300] in "dark" mode
- dark: cyan[700],
+ dark: lightBlue[900], // lightBlue[700] in "dark" mode
}
기본 theme.palette.success 색상 변경
기본 theme.palette.success 색상이 라이트/다크 모드 모두에서 AA 접근성 표준 대비비를 통과하도록 바뀌었어요.
success = {
- main: green[500],
+ main: green[800], // green[400] in "dark" mode
- light: green[300],
+ light: green[500], // green[300] in "dark" mode
- dark: green[700],
+ dark: green[900], // green[700] in "dark" mode
}
기본 theme.palette.warning 색상 변경
기본 theme.palette.warning 색상이 라이트/다크 모드 모두에서 AA 접근성 표준 대비비를 통과하도록 바뀌었어요.
warning = {
- main: orange[500],
+ main: '#ED6C02', // orange[400] in "dark" mode
- light: orange[300],
+ light: orange[500], // orange[300] in "dark" mode
- dark: orange[700],
+ dark: orange[900], // orange[700] in "dark" mode
}
theme.palette.text.hint 키 복원 (필요한 경우)
theme.palette.text.hint 키는 Material UI 컴포넌트에서 사용되지 않았고, 제거됐어요. 이것에 의존한다면 다시 추가할 수 있어요.
import { createTheme } from '@mui/material/styles';
-const theme = createTheme(),
+const theme = createTheme({
+ palette: { text: { hint: 'rgba(0, 0, 0, 0.38)' } },
+});
컴포넌트 정의 재구성 (Restructure component definitions)
테마의 컴포넌트 정의가 찾기 쉽도록 components 키 아래에 재구성됐어요.
1. props
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
- props: {
- MuiButton: {
- disableRipple: true,
- },
- },
+ components: {
+ MuiButton: {
+ defaultProps: {
+ disableRipple: true,
+ },
+ },
+ },
});
2. overrides
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
- overrides: {
- MuiButton: {
- root: { padding: 0 },
- },
- },
+ components: {
+ MuiButton: {
+ styleOverrides: {
+ root: { padding: 0 },
+ },
+ },
+ },
});
@mui/styles
ThemeProvider import 업데이트
@mui/styles의 유틸리티를 @mui/material과 함께 사용한다면, @mui/styles의 ThemeProvider 사용을 @mui/material/styles에서 내보내는 것으로 교체해야 해요.
이렇게 하면 컨텍스트에서 제공되는 theme이 makeStyles, withStyles 등 @mui/styles에서 내보내는 스타일링 유틸리티와 Material UI 컴포넌트 양쪽에서 모두 사용할 수 있게 돼요.
-import { ThemeProvider } from '@mui/styles';
+import { ThemeProvider } from '@mui/material/styles';
@mui/styles에서 오는 유틸리티에는 defaultTheme이 더 이상 없으므로 애플리케이션 루트에 ThemeProvider를 추가해야 해요.
✅ DefaultTheme 모듈 보강 추가 (TypeScript)
@mui/styles 패키지는 더 이상 @mui/material/styles의 일부가 아니에요.
@mui/styles를 @mui/material과 함께 사용한다면 DefaultTheme에 대한 모듈 보강을 추가해야 해요.
// in the file where you are creating the theme (invoking the function `createTheme()`)
import { Theme } from '@mui/material/styles';
declare module '@mui/styles' {
interface DefaultTheme extends Theme {}
}
@mui/material/colors
✅ 색상 import 변경
두 단계 이상의 중첩 import는 private예요. 예를 들어 더 이상 @mui/material/colors/red에서 red를 import할 수 없어요.
-import red from '@mui/material/colors/red';
+import { red } from '@mui/material/colors';
@mui/material/styles
✅ fade를 alpha로 이름 변경
fade()는 기능을 더 잘 설명하기 위해 alpha()로 이름이 바뀌었어요.
이전 이름은 입력 색상에 이미 alpha 값이 있을 때 혼란을 일으켰어요. 그 헬퍼는 색상의 alpha 값을 덮어쓰니까요.
-import { fade } from '@mui/material/styles';
+import { alpha } from '@mui/material/styles';
const classes = makeStyles(theme => ({
- backgroundColor: fade(theme.palette.primary.main, theme.palette.action.selectedOpacity),
+ backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
}));
✅ createStyles import 업데이트
@mui/material/styles의 createStyles 함수가 @mui/styles에서 내보내는 것으로 이동했어요. Material UI npm 패키지에서 @mui/styles에 대한 의존성을 제거하는 데 필요해요.
-import { createStyles } from '@mui/material/styles';
+import { createStyles } from '@mui/styles';
✅ createGenerateClassName import 업데이트
createGenerateClassName 함수는 더 이상 @mui/material/styles에서 내보내지지 않아요. 계속 사용해야 한다면 권장 해제된 @mui/styles 패키지에서 import할 수 있어요.
-import { createGenerateClassName } from '@mui/material/styles';
+import { createGenerateClassName } from '@mui/styles';
@mui/styles를 사용하지 않고 커스텀 클래스 이름을 생성하려면 ClassName Generator를 확인해 보세요.
✅ createMuiTheme 이름 변경
createMuiTheme 함수는 ThemeProvider와 함께 사용할 때 더 직관적이도록 createTheme()으로 이름이 바뀌었어요.
-import { createMuiTheme } from '@mui/material/styles';
+import { createTheme } from '@mui/material/styles';
-const theme = createMuiTheme({
+const theme = createTheme({
✅ MuiThemeProvider import 업데이트
MuiThemeProvider 컴포넌트는 더 이상 @mui/material/styles에서 내보내지지 않아요. 대신 ThemeProvider를 사용하세요.
-import { MuiThemeProvider } from '@mui/material/styles';
+import { ThemeProvider } from '@mui/material/styles';
✅ jssPreset import 업데이트
jssPreset 객체는 더 이상 @mui/material/styles에서 내보내지지 않아요. 계속 사용해야 한다면 권장 해제된 @mui/styles 패키지에서 import할 수 있어요.
-import { jssPreset } from '@mui/material/styles';
+import { jssPreset } from '@mui/styles';
✅ makeStyles import 업데이트
Material UI v5는 JSS를 사용하지 않으므로 JSS 기반 makeStyles 유틸리티는 더 이상 @mui/material/styles에서 내보내지지 않아요. 앱을 JSS에서 마이그레이션하는 동안, 컴포넌트를 더 리팩터링하기 전에 이 권장 해제 유틸리티를 @mui/styles/makeStyles에서 임시로 import할 수 있어요.
defaultTheme이 더 이상 없으므로 애플리케이션 루트에 ThemeProvider를 추가해야 해요.
이 유틸리티를 @mui/material과 함께 사용한다면 @mui/material/styles의 ThemeProvider 컴포넌트를 사용하는 것이 좋아요.
-import { makeStyles } from '@mui/material/styles';
+import { makeStyles } from '@mui/styles';
+import { createTheme, ThemeProvider } from '@mui/material/styles';
+const theme = createTheme();
const useStyles = makeStyles((theme) => ({
background: theme.palette.primary.main,
}));
function Component() {
const classes = useStyles();
return <div className={classes.root} />
}
// In the root of your app
function App(props) {
- return <Component />;
+ return <ThemeProvider theme={theme}><Component {...props} /></ThemeProvider>;
}
✅ ServerStyleSheets import 업데이트
ServerStyleSheets 컴포넌트는 더 이상 @mui/material/styles에서 내보내지지 않아요. 계속 사용해야 한다면 권장 해제된 @mui/styles 패키지에서 import할 수 있어요.
-import { ServerStyleSheets } from '@mui/material/styles';
+import { ServerStyleSheets } from '@mui/styles';
styled
Material UI v5는 JSS를 사용하지 않으므로 @mui/material/styles가 내보내던 JSS 기반 styled 유틸리티는 하위 호환되지 않는 Emotion 기반 유틸리티로 교체됐어요. 앱을 JSS에서 마이그레이션하는 동안, 컴포넌트를 더 리팩터링하기 전에 권장 해제된 @mui/styles 패키지에서 JSS 기반 유틸리티를 임시로 import할 수 있어요.
defaultTheme이 더 이상 없으므로 애플리케이션 루트에 ThemeProvider를 추가해야 해요.
이 유틸리티를 @mui/material과 함께 사용한다면 @mui/material/styles의 ThemeProvider 컴포넌트를 사용하는 것이 좋아요.
-import { styled } from '@mui/material/styles';
+import { styled } from '@mui/styles';
+import { createTheme, ThemeProvider } from '@mui/material/styles';
+const theme = createTheme();
const MyComponent = styled('div')(({ theme }) => ({ background: theme.palette.primary.main }));
function App(props) {
- return <MyComponent />;
+ return <ThemeProvider theme={theme}><MyComponent {...props} /></ThemeProvider>;
}
✅ StylesProvider import 업데이트
StylesProvider 컴포넌트는 더 이상 @mui/material/styles에서 내보내지지 않아요. 계속 사용해야 한다면 권장 해제된 @mui/styles 패키지에서 import할 수 있어요.
-import { StylesProvider } from '@mui/material/styles';
+import { StylesProvider } from '@mui/styles';
✅ useThemeVariants import 업데이트
useThemeVariants 훅은 더 이상 @mui/material/styles에서 내보내지지 않아요. 계속 사용해야 한다면 권장 해제된 @mui/styles 패키지에서 import할 수 있어요.
-import { useThemeVariants } from '@mui/material/styles';
+import { useThemeVariants } from '@mui/styles';
✅ withStyles import 업데이트
Material UI v5는 JSS를 사용하지 않으므로 JSS 기반 withStyles 유틸리티는 더 이상 @mui/material/styles에서 내보내지지 않아요. 앱을 JSS에서 마이그레이션하는 동안, 컴포넌트를 더 리팩터링하기 전에 이 권장 해제 유틸리티를 @mui/styles/withStyles에서 임시로 import할 수 있어요.
defaultTheme이 더 이상 없으므로 애플리케이션 루트에 ThemeProvider를 추가해야 해요.
이 유틸리티를 @mui/material과 함께 사용한다면 @mui/material/styles의 ThemeProvider 컴포넌트를 사용해야 해요.
-import { withStyles } from '@mui/material/styles';
+import { withStyles } from '@mui/styles';
+import { createTheme, ThemeProvider } from '@mui/material/styles';
+const defaultTheme = createTheme();
const MyComponent = withStyles((props) => {
const { classes, className, ...other } = props;
return <div className={clsx(className, classes.root)} {...other} />
})(({ theme }) => ({ root: { background: theme.palette.primary.main }}));
function App() {
- return <MyComponent />;
+ return <ThemeProvider theme={defaultTheme}><MyComponent /></ThemeProvider>;
}
✅ innerRef를 ref로 교체
innerRef prop을 ref prop으로 교체해요. refs는 이제 내부 컴포넌트로 자동 전달돼요.
import * as React from 'react';
import { withStyles } from '@mui/styles';
const MyComponent = withStyles({
root: {
backgroundColor: 'red',
},
})(({ classes }) => <div className={classes.root} />);
function MyOtherComponent(props) {
const ref = React.useRef();
- return <MyComponent innerRef={ref} />;
+ return <MyComponent ref={ref} />;
}
withTheme import 업데이트
withTheme HOC 유틸리티가 @mui/material/styles 패키지에서 제거됐어요. @mui/styles/withTheme을 대신 사용할 수 있어요.
defaultTheme이 더 이상 없으므로 애플리케이션 루트에 ThemeProvider를 추가해야 해요.
이 유틸리티를 @mui/material과 함께 사용한다면 @mui/material/styles의 ThemeProvider 컴포넌트를 사용하는 것이 좋아요.
-import { withTheme } from '@mui/material/styles';
+import { withTheme } from '@mui/styles';
+import { createTheme, ThemeProvider } from '@mui/material/styles';
+const theme = createTheme();
const MyComponent = withTheme(({ theme }) => <div>{theme.direction}</div>);
function App(props) {
- return <MyComponent />;
+ return <ThemeProvider theme={theme}><MyComponent {...props} /></ThemeProvider>;
}
✅ withWidth 제거
이 HOC는 제거됐어요. 이 기능이 필요하다면 useMediaQuery 훅을 사용하는 대안을 시도할 수 있어요.
@mui/icons-material
GitHub 아이콘 크기 줄이기
GitHub 아이콘이 다른 아이콘들의 크기에 맞추어 24px에서 22px 너비로 줄었어요.
@material-ui/pickers
@material-ui/pickers를 v5로 마이그레이션하기 위한 전용 페이지가 있어요.
System
✅ gap props 이름 변경
다음 system 함수와 속성들이 권장 해제된 CSS로 간주되어 이름이 바뀌었어요.
gridGap은gap이 됨gridRowGap은rowGap이 됨gridColumnGap은columnGap이 됨
✅ gap props에 간격 단위 추가
gap, rowGap, columnGap에 간격 단위를 사용하세요. 이전에 숫자를 사용했다면 theme.spacing의 새 변환을 우회하려면 px을 명시해야 해요.
<Box
- gap={2}
+ gap="2px"
>
styled-components와 Emotion의 css prop과의 충돌을 피하려면 css prop을 sx로 교체해요.
-<Box css={{ color: 'primary.main' }} />
+<Box sx={{ color: 'primary.main' }} />
:::warning system grid 함수는 v4에서 문서화되지 않았어요. :::