테마된 컴포넌트 만들기
테마된 컴포넌트 만들기 (Creating themed components)
앱의 테마를 받아들이는 완전한 커스텀 컴포넌트를 만드는 방법을 배워보세요.
출처: 문서
본문
소개 (Introduction)
Material UI는 내장 컴포넌트인 것처럼 취급할 수 있도록 자신만의 컴포넌트를 테마에 추가할 수 있는 강력한 테마 기능을 제공합니다.
Material UI를 기반으로 컴포넌트 라이브러리를 구축하고 있다면, 아래의 단계별 가이드를 따라 여러 프로젝트에서 테마를 적용할 수 있는 커스텀 컴포넌트를 만들 수 있습니다.
또는 제공된 템플릿을 컴포넌트의 시작점으로 사용할 수 있습니다.
:::info 단일 프로젝트에서만 컴포넌트를 사용한다면 테마에 연결할 필요가 없습니다. :::
단계별 가이드 (Step-by-step guide)
이 가이드는 앱의 테마를 마치 내장된 Material UI 컴포넌트처럼 받아들이는 다음 통계(statistics) 컴포넌트를 구축하는 방법을 안내합니다:
{{"demo": "StatComponent.js", "hideToolbar": true}}
1. 컴포넌트 슬롯 만들기
슬롯(Slots)을 사용하면 테마의 styleOverrides와 테마의 variants에서 각각의 이름을 대상으로 지정하여 컴포넌트의 개별 요소를 커스터마이즈할 수 있습니다.
이 통계 컴포넌트는 세 개의 슬롯으로 구성됩니다:
root: 컴포넌트의 컨테이너value: 통계의 숫자unit: 통계의 단위 또는 설명
:::success
이 슬롯에 원하는 이름을 붙일 수 있지만, 라이브러리의 나머지 부분과 일관성을 위해 가장 바깥쪽 컨테이너 요소에는 root를 사용할 것을 권장합니다.
:::
{{"demo": "StatSlots.js", "hideToolbar": true}}
아래처럼 name과 slot 매개변수와 함께 styled API를 사용해 슬롯을 만드세요:
import * as React from 'react';
import { styled } from '@mui/material/styles';
const StatRoot = styled('div', {
name: 'MuiStat', // The component name
slot: 'root', // The slot name
})(({ theme }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(0.5),
padding: theme.spacing(3, 4),
backgroundColor: theme.palette.background.paper,
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[2],
letterSpacing: '-0.025em',
fontWeight: 600,
...theme.applyStyles('dark', {
backgroundColor: 'inherit',
}),
}));
const StatValue = styled('div', {
name: 'MuiStat',
slot: 'value',
})(({ theme }) => ({
...theme.typography.h3,
}));
const StatUnit = styled('div', {
name: 'MuiStat',
slot: 'unit',
})(({ theme }) => ({
...theme.typography.body2,
color: theme.palette.text.secondary,
}));
2. 컴포넌트 만들기
이전 단계에서 만든 슬롯을 사용해 컴포넌트를 조립하세요:
// /path/to/Stat.js
import * as React from 'react';
const StatRoot = styled('div', {
name: 'MuiStat',
slot: 'root',
})(…);
const StatValue = styled('div', {
name: 'MuiStat',
slot: 'value',
})(…);
const StatUnit = styled('div', {
name: 'MuiStat',
slot: 'unit',
})(…);
const Stat = React.forwardRef(function Stat(props, ref) {
const { value, unit, ...other } = props;
return (
<StatRoot ref={ref} {...other}>
<StatValue>{value}</StatValue>
<StatUnit>{unit}</StatUnit>
</StatRoot>
);
});
export default Stat;
이 시점에서 아래처럼 Stat 컴포넌트에 테마를 적용할 수 있습니다:
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
components: {
// the component name defined in the `name` parameter
// of the `styled` API
MuiStat: {
styleOverrides: {
// the slot name defined in the `slot` and `overridesResolver` parameters
// of the `styled` API
root: {
backgroundColor: '#121212',
},
value: {
color: '#fff',
},
unit: {
color: '#888',
},
},
},
},
});
3. ownerState로 슬롯 스타일링하기
슬롯 기반 props나 내부 상태를 스타일링해야 할 때는 ownerState 객체에 감싸 각 슬롯에 prop으로 전달하세요.
ownerState는 styled API를 통해 DOM에 펼쳐지지 않는 특별한 이름입니다.
아래처럼 Stat 컴포넌트에 variant prop을 추가하고 이를 사용해 root 슬롯을 스타일링하세요:
const Stat = React.forwardRef(function Stat(props, ref) {
+ const { value, unit, variant, ...other } = props;
+
+ const ownerState = { ...props, variant };
return (
- <StatRoot ref={ref} {...other}>
- <StatValue>{value}</StatValue>
- <StatUnit>{unit}</StatUnit>
- </StatRoot>
+ <StatRoot ref={ref} ownerState={ownerState} {...other}>
+ <StatValue ownerState={ownerState}>{value}</StatValue>
+ <StatUnit ownerState={ownerState}>{unit}</StatUnit>
+ </StatRoot>
);
});
그런 다음 슬롯에서 ownerState를 읽어 variant prop을 기반으로 스타일링할 수 있습니다.
const StatRoot = styled('div', {
name: 'MuiStat',
slot: 'root',
- })(({ theme }) => ({
+ })(({ theme, ownerState }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(0.5),
padding: theme.spacing(3, 4),
backgroundColor: theme.palette.background.paper,
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[2],
letterSpacing: '-0.025em',
fontWeight: 600,
...theme.applyStyles('dark', {
backgroundColor: 'inherit',
}),
+ ...ownerState.variant === 'outlined' && {
+ border: `2px solid ${theme.palette.divider}`,
+ },
}));
4. 테마 기본 props 지원하기
다양한 프로젝트에 맞게 컴포넌트의 기본 props를 커스터마이즈하려면 useThemeProps API를 사용해야 합니다.
+ import { useThemeProps } from '@mui/material/styles';
- const Stat = React.forwardRef(function Stat(props, ref) {
+ const Stat = React.forwardRef(function Stat(inProps, ref) {
+ const props = useThemeProps({ props: inProps, name: 'MuiStat' });
const { value, unit, ...other } = props;
return (
<StatRoot ref={ref} {...other}>
<StatValue>{value}</StatValue>
<StatUnit>{unit}</StatUnit>
</StatRoot>
);
});
그런 다음 컴포넌트의 기본 props를 다음과 같이 커스터마이즈할 수 있습니다:
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
components: {
MuiStat: {
defaultProps: {
variant: 'outlined',
},
},
},
});
TypeScript
TypeScript를 사용한다면 컴포넌트 props와 ownerState에 대한 인터페이스를 만들어야 합니다:
interface StatProps {
value: number | string;
unit: string;
variant?: 'outlined';
}
interface StatOwnerState extends StatProps {
// …key value pairs for the internal state that you want to style the slot
// but don't want to expose to the users
}
그런 다음 컴포넌트와 슬롯에서 사용할 수 있습니다.
const StatRoot = styled('div', {
name: 'MuiStat',
slot: 'root',
})<{ ownerState: StatOwnerState }>(({ theme, ownerState }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(0.5),
padding: theme.spacing(3, 4),
backgroundColor: theme.palette.background.paper,
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[2],
letterSpacing: '-0.025em',
fontWeight: 600,
...theme.applyStyles('dark', {
backgroundColor: 'inherit',
}),
// typed-safe access to the `variant` prop
...(ownerState.variant === 'outlined' && {
border: `2px solid ${theme.palette.divider}`,
boxShadow: 'none',
}),
}));
// …do the same for other slots
const Stat = React.forwardRef<HTMLDivElement, StatProps>(function Stat(inProps, ref) {
const props = useThemeProps({ props: inProps, name: 'MuiStat' });
const { value, unit, variant, ...other } = props;
const ownerState = { ...props, variant };
return (
<StatRoot ref={ref} ownerState={ownerState} {...other}>
<StatValue ownerState={ownerState}>{value}</StatValue>
<StatUnit ownerState={ownerState}>{unit}</StatUnit>
</StatRoot>
);
});
마지막으로 Stat 컴포넌트를 테마 타입에 추가하세요.
import {
ComponentsOverrides,
ComponentsVariants,
Theme as MuiTheme,
} from '@mui/material/styles';
import { StatProps } from 'path/to/Stat';
type Theme = Omit<MuiTheme, 'components'>;
declare module '@mui/material/styles' {
interface ComponentNameToClassKey {
MuiStat: 'root' | 'value' | 'unit';
}
interface ComponentsPropsList {
MuiStat: Partial<StatProps>;
}
interface Components {
MuiStat?: {
defaultProps?: ComponentsPropsList['MuiStat'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStat'];
variants?: ComponentsVariants['MuiStat'];
};
}
}
템플릿 (Template)
이 템플릿은 위 단계별 가이드의 최종 결과물로, 내장 컴포넌트처럼 테마로 스타일링할 수 있는 커스텀 컴포넌트를 구축하는 방법을 보여줍니다.
{{"demo": "StatFullTemplate.js", "defaultCodeOpen": true}}