`styled()`
styled()
styled 컴포넌트를 만드는 유틸리티예요.
출처: 문서
본문
소개 (Introduction)
모든 Material UI 컴포넌트는 styled() 유틸리티로 스타일링돼요.
이 유틸리티는 @mui/styled-engine의 styled() 모듈 위에 만들어졌고, 추가 기능을 제공해요.
import 경로 (Import path)
@mui/system 패키지에서 유틸리티를 가져올 수 있어요. @mui/material을 사용한다면 @mui/material/styles에서 가져올 수도 있어요.
차이점은 사용되는 기본 theme에 있어요 (React 컨텍스트에 사용 가능한 theme가 없을 때의 기본값).
import { styled } from '@mui/system';
// If you are using @mui/material
import { styled } from '@mui/material/styles';
어떤 문제를 해결하나요? (What problems does it solve?)
이 유틸리티는 emotion이나 styled-components의 styled() 유틸리티를 대체하는 용도로 쓸 수 있어요. 같은 문제를 해결하기 위한 것이지만, 다음과 같은 이점도 추가로 제공해요:
- React 컨텍스트에 theme가 없으면 기본
theme을 사용해요. - options에 지정한
name을 기준으로 테마의styleOverrides와variants가 적용되도록 지원해요 (생략 가능). - 결과 컴포넌트에서 the
sxprop을 지원해요 (생략 가능). - 기본적으로
shouldForwardProp옵션(ownerState,theme,sx,as를 고려함)을 추가해요 (오버라이드 가능).
API
styled(Component, [options])(styles) => Component
인자 (Arguments)
-
Component: 감싸질 컴포넌트. -
options(object [선택]):options.shouldForwardProp((prop: string) => bool[선택]): 해당prop을Component로 전달할지 여부를 나타내요.options.label(string [선택]): 스타일 시트의 접미사. 디버깅에 유용해요.options.name(string [선택]):theme.components아래에서styleOverrides와variants를 지정하는 키.label생성에도 사용돼요.options.slot(string [선택]):Root이면 테마의variants를 자동으로 적용해요.options.overridesResolver((props: object, styles: Record<string, styles>) => styles [선택]): props와theme.components[name].styleOverrides객체를 기반으로 스타일을 반환하는 함수.options.skipVariantsResolver(bool):theme.components[name].variants에 대한 자동 해석기(resolver)를 비활성화해요.options.skipSx(bool [선택]): 컴포넌트의sxprop을 비활성화해요.- 나머지 키들은 emotion의
styled([Component], [options])의options인자로 전달돼요.
-
styles(object |({ ...props, theme }) => object[선택]): 스타일 객체 또는 스타일 객체를 반환하는 함수. 이 함수는 단일 인자로 theme와 컴포넌트 props를 담은 객체를 받아요.
반환 값 (Returns)
Component: 새로 만들어진 컴포넌트.
기본 사용법 (Basic usage)
## theme 사용하기 (Using the theme)
```jsx demo="ThemeUsage.js"
## 커스텀 컴포넌트 (Custom components)
이 예시는 `styled` API를 사용해서 핵심 컴포넌트와 같은 기능을 가진 커스텀 컴포넌트를 만드는 방법을 보여줘요:
```jsx demo="UsingOptions.js"
개발 모드에서 브라우저 DevTools로 이 요소를 검사해 보면, 컴포넌트의 클래스가 제공된 `name`과 `slot` 옵션에서 오는 `MyThemeComponent-root`로 끝나는 걸 볼 수 있어요.
<img src="/static/images/system/styled-options.png" alt="browser DevTools showing the rendered component" width="654" height="258" style="width: 327px" />
여기에 더해, `color`, `sx`, `variant` prop은 생성된 `div` 요소로 전파되지 않아요.
## 기능 제거하기 (Removing features)
MUI System 특화 기능 중 일부를 제거하고 싶다면 이렇게 하면 돼요:
```diff
const StyledComponent = styled('div', {}, {
name: 'MuiStyled',
slot: 'Root',
- overridesResolver: (props, styles) => styles.root, // disables theme.components[name].styleOverrides
+ skipVariantsResolver: true, // disables theme.components[name].variants
+ skipSx: true, // disables the sx prop
});
커스텀 styled() 유틸리티 만들기
styled() 유틸리티에 다른 기본 theme를 쓰고 싶다면, createStyled() 유틸리티를 사용해서 나만의 버전을 만들 수 있어요.
import { createStyled, createTheme } from '@mui/system';
const defaultTheme = createTheme({
// your custom theme values
});
const styled = createStyled({ defaultTheme });
export default styled;
sx prop과의 차이점 (Difference with the sx prop)
styled 함수는 내부에서 사용하는 스타일 라이브러리(Emotion 또는 styled-components)가 제공하는 styled 유틸리티의 확장이에요.
같은 입력에 대해 스타일 라이브러리에서 온 styled 함수와 동일한 출력을 만드는 것이 보장돼요.
반면 sx prop은 빠른 커스터마이징에 초점을 맞춘, 컴포넌트를 스타일링하는 새로운 방식이에요. styled는 함수이고, sx는 styled로 만든 컴포넌트에서 사용할 수 있는 prop이에요.
따라서 다음과 같은 차이점들을 볼 수 있어요:
sx가 styled보다 더 많은 축약어를 제공해요
styled 사용 시:
const MyStyledButton = styled('button')({
mx: 1, // ❌ don't use this! This shortcut is only provided by the `sx` prop
});
sx 사용 시:
import Button from '@mui/material/Button';
const MyStyledButton = (props) => (
<Button
sx={{
mx: 1, // ✔️ this shortcut is specific to the `sx` prop,
}}
>
{props.children}
</Button>
);
스타일 정의 방식이 약간 달라요
styled 사용 시:
const MyStyledButton = styled('button')({
padding: 1, // means "1px", NOT "theme.spacing(1)"
});
sx 사용 시:
import Button from '@mui/material/Button';
const MyStyledButton = (props) => (
<Button
sx={{
padding: 1, // means "theme.spacing(1)", NOT "1px"
}}
>
{props.children}
</Button>
);
props 사용 패턴이 달라요
styled 사용 시:
const MyStyledButton = styled('button')((props) => ({
backgroundColor: props.myBackgroundColor,
}));
sx 사용 시:
import Button from '@mui/material/Button';
const MyStyledButton = (props) => (
<Button sx={{ backgroundColor: props.myCustomColor }}>{props.children}</Button>
);
함수를 사용할 때 각 필드의 매개변수가 달라요
styled 사용 시 (권장하지 않음):
// You may find this syntax in the wild, but for code readability
// we recommend using only one top-level function
const MyStyledButtonPropsPerField = styled('button')({
backgroundColor: (props) => props.myBackgroundColor,
});
sx 사용 시:
import Button from '@mui/material/Button';
import { lighten } from 'polished';
const MyStyledButton = (props) => (
<Button
sx={{ backgroundColor: (theme) => lighten(0.2, theme.palette.primary.main) }}
>
{props.children}
</Button>
);
// Note: for direct theme access without modification, you can also use a shortcut by providing the key as a string
const MyStyledButton = (props) => (
<Button sx={{ backgroundColor: 'primary.main' }}>{props.children}</Button>
);
styled() 유틸리티에서 sx 문법을 어떻게 쓸 수 있나요? (How can I use the sx syntax with the styled() utility?)
sx 문법을 더 선호하고 sx prop과 styled() 유틸리티 양쪽에서 쓰고 싶다면, theme의 unstable_sx 유틸리티를 사용할 수 있어요:
`unstable_sx` 유틸리티를 사용할 때 추가되는 오버헤드는 컴포넌트에 `sx` prop을 사용할 때와 같아요.
:::info
참고: `unstable_sx`는 `styled()` 유틸리티 밖에서도 사용할 수 있어요. 예를 들어 커스텀 테마에서 `variants`를 정의할 때도 쓸 수 있어요.
:::
## 컴포넌트 선택자 API 사용법 (How to use components selector API)
[`emotion`](https://emotion.sh/docs/styled#targeting-another-emotion-component)이나 [`styled-components`](https://styled-components.com/docs/advanced#referring-to-other-components)의 `styled()` API를 사용해 본 적이 있다면, 컴포넌트를 선택자로 사용할 수 있었을 거예요.
```jsx
import styled from '@emotion/styled';
const Child = styled.div`
color: red;
`;
const Parent = styled.div`
${Child} {
color: green;
}
`;
render(
<div>
<Parent>
<Child>Green because I am inside a Parent</Child>
</Parent>
<Child>Red because I am not inside a Parent</Child>
</div>,
);
MUI System의 styled() 유틸리티에서도 컴포넌트를 선택자로 사용할 수 있어요. @mui/styled-engine-sc(styled-components)를 사용할 때는 아무것도 할 필요가 없어요. 기본 엔진인 @mui/styled-engine(emotion)을 사용할 때는 몇 가지 단계를 수행해야 해요:
먼저 @emotion/babel-plugin을 설치해야 해요.
npm install @emotion/babel-plugin
그런 다음 플러그인에 Material UI 버전의 styled() 유틸리티를 알려 주도록 구성해요:
babel.config.js
module.exports = {
...
plugins: [
[
"@emotion",
{
importMap: {
"@mui/system": {
styled: {
canonicalImport: ["@emotion/styled", "default"],
styledBaseImport: ["@mui/system", "styled"]
}
},
"@mui/material": {
styled: {
canonicalImport: ["@emotion/styled", "default"],
styledBaseImport: ["@mui/material", "styled"]
}
},
"@mui/material/styles": {
styled: {
canonicalImport: ["@emotion/styled", "default"],
styledBaseImport: ["@mui/material/styles", "styled"]
}
}
}
}
]
]
};
:::info
참고: babel-plugin-direct-import를 사용한다면, Babel 설정에서 @emotion/babel-plugin 뒤에 배치하세요.
:::
이제 컴포넌트를 선택자로 사용할 수 있을 거예요!