sx prop
sx prop은 테마에 접근할 수 있는 커스텀 스타일을 정의하기 위한 지름길이에요.
출처: 문서
본문
sx prop은 @mui/system이 노출하는 모든 스타일 함수를 묶어 놓은 CSS의 슈퍼셋(superset)으로 작업할 수 있게 해 줘요.
이 prop으로 유효한 CSS를 얼마든지 지정할 수 있고, MUI System에만 있는 많은 테마 인지(theme-aware) 프로퍼티도 사용할 수 있어요.
기본 예시
다음 데모는 sx prop을 어떻게 사용하는지 보여줘요.
값 중 일부는 유효한 CSS 프로퍼티가 아니라는 점에 주목하세요. sx 키는 테마의 특정 프로퍼티로 매핑되기 때문이에요.
이 문서의 나머지 부분에서 이 개념을 더 자세히 살펴볼게요.
테마 인지 프로퍼티
테두리 (Borders)
border 프로퍼티는 값으로 숫자만 받을 수 있어요.
숫자로 픽셀 단위의 굵기를 정하고, 실선 검은색 테두리를 만들어 줘요.
<Box sx={{ border: 1 }} />
// equivalent to border: '1px solid black'
borderColor 프로퍼티는 문자열을 받을 수 있는데, 이 문자열은 theme.palette 안의 경로를 나타내요.
<Box sx={{ borderColor: 'primary.main' }} />
// equivalent to borderColor: theme => theme.palette.primary.main
borderRadius 프로퍼티는 받은 값을 theme.shape.borderRadius 값(기본값은 4px)에 곱해요.
<Box sx={{ borderRadius: 2 }} />
// equivalent to borderRadius: theme => 2 * theme.shape.borderRadius
더 자세한 내용은 Borders 페이지에서 확인하세요.
표시 (Display)
displayPrint 프로퍼티로, 인쇄할 때만 적용되는 CSS display 값을 지정할 수 있어요.
<Box sx={{ displayPrint: 'none' }} /> // equivalent to '@media print': { display: 'none' }
더 자세한 내용은 Display 페이지에서 확인하세요.
그리드 (Grid)
CSS Grid 프로퍼티인 gap, rowGap, columnGap은 받은 값을 theme.spacing 값(기본값은 8px)에 곱해요.
<Box sx={{ gap: 2 }} />
// equivalent to gap: theme => theme.spacing(2)
더 자세한 내용은 Grid 페이지에서 확인하세요.
팔레트 (Palette)
color와 backgroundColor 프로퍼티는 문자열을 받을 수 있는데, 이 문자열은 theme.palette 안의 경로를 나타내요.
<Box sx={{ color: 'primary.main' }} />
// equivalent to color: theme => theme.palette.primary.main
backgroundColor 프로퍼티는 별칭 bgcolor로도 사용할 수 있어요.
<Box sx={{ bgcolor: 'primary.main' }} />
// equivalent to backgroundColor: theme => theme.palette.primary.main
더 자세한 내용은 Palette 페이지에서 확인하세요.
위치 (Positions)
zIndex 프로퍼티는 값을 theme.zIndex 값에 매핑해요.
<Box sx={{ zIndex: 'tooltip' }} />
// equivalent to zIndex: theme => theme.zIndex.tooltip
더 자세한 내용은 Positions 페이지에서 확인하세요.
그림자 (Shadows)
boxShadow 프로퍼티는 값을 theme.shadows 값에 매핑해요.
<Box sx={{ boxShadow: 1 }} />
// equivalent to boxShadow: theme => theme.shadows[1]
더 자세한 내용은 Shadows 페이지에서 확인하세요.
크기 (Sizing)
sizing 프로퍼티인 width, height, minHeight, maxHeight, minWidth, maxWidth는 값을 변환하는 다음 커스텀 함수를 사용해요.
function transform(value) {
return value <= 1 && value !== 0 ? `${value * 100}%` : value;
}
값이 (0, 1] 사이에 있으면 백분율로 변환돼요. 그 외에는 CSS 프로퍼티에 그대로 설정돼요.
<Box sx={{ width: 1/2 }} /> // equivalent to width: '50%'
<Box sx={{ width: 20 }} /> // equivalent to width: '20px'
더 자세한 내용은 Sizing 페이지에서 확인하세요.
간격 (Spacing)
spacing 프로퍼티인 margin, padding과 대응하는 longhand 프로퍼티들은 받은 값을 theme.spacing 값(기본값은 8px)에 곱해요.
<Box sx={{ margin: 2 }} />
// equivalent to margin: theme => theme.spacing(2)
spacing 프로퍼티에는 다음 별칭이 제공돼요.
| Prop | CSS property |
|---|---|
m |
margin |
mt |
margin-top |
mr |
margin-right |
mb |
margin-bottom |
ml |
margin-left |
mx |
margin-left, margin-right |
my |
margin-top, margin-bottom |
p |
padding |
pt |
padding-top |
pr |
padding-right |
pb |
padding-bottom |
pl |
padding-left |
px |
padding-left, padding-right |
py |
padding-top, padding-bottom |
더 자세한 내용은 Spacing 페이지에서 확인하세요.
타이포그래피 (Typography)
fontFamily, fontSize, fontStyle, fontWeight 프로퍼티는 값을 theme.typography 값에 매핑해요.
<Box sx={{ fontWeight: 'fontWeightLight' }} />
// equivalent to fontWeight: theme.typography.fontWeightLight
CSS 프로퍼티 접두사 fontWeight를 생략해도 같은 결과를 얻을 수 있어요.
<Box sx={{ fontWeight: 'light' }} />
// equivalent to fontWeight: theme.typography.fontWeightLight
또한 특정 theme.typography 변형(variant)에 정의된 모든 값을 설정하는 typography prop이 추가로 있어요.
<Box sx={{ typography: 'body1' }} />
// equivalent to { ...theme.typography.body1 }
더 자세한 내용은 Typography 페이지에서 확인하세요.
반응형 값 (Responsive values)
sx prop과 관련된 모든 프로퍼티는 특정 브레이크포인트와 컨테이너 쿼리에 대한 반응형 값도 지원해요.
자세한 내용은 Usage 페이지—Responsive values에서 확인하세요.
콜백 값 (Callback values)
객체인 테마 값을 가져와야 할 때 콜백을 사용하세요.
<Box
sx={(theme) => ({
...theme.typography.body,
color: theme.palette.primary.main,
})}
/>
:::info 값으로서의 콜백은 deprecated되었어요. 대신 콜백 자체를 값 전체로 사용해 주세요.
- sx={{ height: (theme) => theme.spacing(10) }}
+ sx={(theme) => ({ height: theme.spacing(10) })}
코드는 우리 codemod로 마이그레이션할 수 있어요.
npx @mui/codemod@latest v6.0.0/sx-prop path/to/file-or-folder
:::
TypeScript에서 sx prop 콜백과 함께 커스텀 테마 프로퍼티를 사용하려면, module augmentation으로 @mui/system 라이브러리의 Theme 타입을 확장하세요.
import * as React from 'react';
import Box from '@mui/material/Box';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { orange } from '@mui/material/colors';
declare module '@mui/system' {
interface Theme {
status: {
warning: string;
};
}
}
const theme = createTheme({
status: {
warning: orange[500],
},
});
export default function App() {
return (
<ThemeProvider theme={theme}>
<Box
sx={(theme) => ({
bgcolor: theme.status.warning,
})}
>
Example
</Box>
</ThemeProvider>
);
}
배열 값 (Array values)
이전 인덱스의 일부 스타일을 부분적으로 덮어쓰고 싶을 때 배열 타입이 유용해요.
<Box
sx={[
{
'&:hover': {
color: 'red',
backgroundColor: 'white',
},
},
foo && {
'&:hover': { backgroundColor: 'grey' },
},
bar && {
'&:hover': { backgroundColor: 'yellow' },
},
]}
/>
이 요소에 hover하면 color: red; backgroundColor: white;가 적용돼요.
foo: true면, hover할 때 color: red; backgroundColor: grey;가 적용돼요.
bar: true면, foo 값과 상관없이 hover할 때 color: red; backgroundColor: yellow;가 적용돼요. 배열에서 더 높은 인덱스가 더 높은 특이성(specificity)을 가지기 때문이에요.
:::info 각 인덱스는 객체 또는 콜백이 될 수 있어요. :::
<Box
sx={[
{ mr: 2, color: 'red' },
(theme) => ({
'&:hover': {
color: theme.palette.primary.main,
},
}),
]}
/>
sx prop 전달하기
커스텀 컴포넌트에서 sx prop을 받아서 다른 MUI System으로 전달하고 싶다면, 이 방식을 권해요.
동적 값 (Dynamic values)
매우 동적인 CSS 값에는, 매 렌더링마다 값이 변하는 객체를 sx prop에 넘기는 대신 인라인 CSS 변수를 사용하는 걸 권해요.
이렇게 하면 불필요한 style 태그가 DOM에 삽입되는 걸 피할 수 있어서, 자주 바뀔 수 있는 넓은 범위의 값을 다루는 CSS 프로퍼티(예: 라이브 미리보기가 있는 컬러 피커)에서 잠재적인 성능 문제를 막아줘요.
:::info
style 속성으로 인라인 스타일을 쓸 때 Content Security Policy 관련 문제가 있다면, style-src-attr 디렉티브를 활성화했는지 확인하세요.
설정 방법은 Content Security Policy 가이드를 참고하세요.
:::
:::warning
sx 안의 값은 스타일시트에 그대로 쓰여요. 그래서 }를 포함한 값이 규칙을 끝내고 자신만의 CSS를 추가할 수도 있어요.
값이 사용자 입력에서 온 거라면, 사용 전에 기대하는 형식과 일치하는지 검사하세요. 예를 들어 컬러 피커의 색상은 /^#[0-9a-f]{6}$/i, 크기는 Number()처럼요.
테마 값과 GlobalStyles에도 같은 내용이 적용돼요.
:::
TypeScript 사용법
sx prop에서 자주 혼란을 주는 원인 중 하나는 TypeScript의 type widening이에요. 이 때문에 다음 예시가 예상대로 동작하지 않아요.
const style = {
flexDirection: 'column',
};
export default function App() {
return <Button sx={style}>Example</Button>;
}
// Type '{ flexDirection: string; }' is not assignable to type 'SxProps<Theme> | undefined'
// Type '{ flexDirection: string; }' is not assignable to type 'CSSSelectorObject<Theme>'
// Property 'flexDirection' is incompatible with index signature
// Type 'string' is not assignable to type 'SystemStyleObject<Theme>'
문제는 flexDirection prop의 타입이 string으로 추론되는데, 이게 너무 넓다는 거예요.
해결하려면 sx prop에 넘기는 객체/함수를 const로 캐스팅하면 돼요.
const style = {
flexDirection: 'column',
} as const;
export default function App() {
return <Button sx={style}>Example</Button>;
}
또는 스타일 객체를 sx prop에 직접 전달할 수도 있어요.
export default function App() {
return <Button sx={{ flexDirection: 'column' }}>Example</Button>;
}
성능 (Performance)
sx prop의 성능 트레이드오프에 대해 더 알아보려면 Usage–Performance tradeoffs를 확인하세요.