본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Themed components

원문 보기 위키 갱신

테마 안에서 컴포넌트 키를 사용하면 컴포넌트의 스타일, 기본 props 등을 원하는 대로 바꿀 수 있어요.

출처: 문서

본문

테마의 components 키는 앱 전체에서 스타일 일관성을 잡아 주는 데 도움을 줘요. 다만 테마는 트리 셰이킹(tree-shaking)이 되지 않기 때문에, 커스터마이징이 무거워진다면 새 컴포넌트를 만드는 쪽을 더 선호해요.

테마 기본 props

모든 Material UI 컴포넌트는 각 prop마다 기본값을 가지고 있어요. 이 기본값을 바꾸려면 테마의 components 키에 노출된 defaultProps 키를 사용해 주세요.

const theme = createTheme({
  components: {
    // Name of the component
    MuiButtonBase: {
      defaultProps: {
        // The props to change the default for.
        disableRipple: true, // No more ripple, on the whole application 💣!
      },
    },
  },
});
{{"demo": "DefaultProps.js"}}

TypeScript와 lab 컴포넌트를 사용한다면, 이 문서에서 그들의 스타일을 오버라이드하는 방법을 확인해 보세요.

테마 스타일 오버라이드

테마의 styleOverrides 키를 사용하면 어떤 Material UI 컴포넌트의 기본 스타일도 바꿀 수 있어요.

styleOverrides는 키로 슬롯(slot) 이름을 요구하고(가장 바깥 요소를 대상으로 하려면 root를 사용), 값으로는 CSS 속성 객체를 요구해요. 값으로 중첩된 CSS 선택자도 지원돼요.

const theme = createTheme({
  components: {
    // Name of the component
    MuiButton: {
      styleOverrides: {
        // Name of the slot
        root: {
          // Some CSS
          fontSize: '1rem',
        },
      },
    },
  },
});
{{"demo": "GlobalThemeOverride.js"}}

Variants

대부분의 컴포넌트는 외형에 영향을 주는 디자인 관련 props를 포함해요. 예를 들어 Card 컴포넌트는 outlined라는 값을 선택하면 테두리가 추가되는 variant prop을 지원해요.

특정 prop에 기반해 스타일을 오버라이드하려면, 해당 슬롯의 variants 키를 사용할 수 있어요. variants의 각 항목은 props 키와 style 키를 담고 있고, 컴포넌트의 props가 일치하면 style이 적용돼요.

오버라이드 정의는 배열로 지정해요. 또한 우선순위가 있어야 하는 스타일은 마지막에 나열하는 걸 잊지 마세요.

기존 props에 기반한 스타일 오버라이드

아래 예시는 outlined인 Card의 테두리 두께를 늘리는 방법을 보여 줘요.

const theme = createTheme({
  components: {
    MuiCard: {
      styleOverrides: {
        root: {
          variants: [
            {
              props: { variant: 'outlined' },
              style: {
                borderWidth: '3px',
              },
            },
          ],
        },
      },
    },
  },
});

새 값에 기반한 스타일 추가

아래 예시는 Button 컴포넌트에 dashed라는 새 variant를 추가하는 방법이에요.

const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          variants: [
            {
              // `dashed` is an example value, it can be any name.
              props: { variant: 'dashed' },
              style: {
                textTransform: 'none',
                border: `2px dashed ${blue[500]}`,
              },
            },
          ],
        },
      },
    },
  },
});

기존 prop과 새 prop에 함께 기반한 스타일 오버라이드

아래 예시는 Button의 variant가 dashed(새 variant)이고 color가 secondary(기존 color)일 때의 스타일 오버라이드예요.

const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          variants: [
            {
              props: { variant: 'dashed', color: 'secondary' },
              style: {
                border: `4px dashed ${red[500]}`,
              },
            },
          ],
        },
      },
    },
  },
});

TypeScript를 사용한다면 모듈 증강(module augmentation)으로 새 variant/color를 지정해야 해요.

declare module '@mui/material/Button' {
  interface ButtonPropsVariantOverrides {
    dashed: true;
  }
}
{{"demo": "GlobalThemeVariants.js"}}

variant의 props는 콜백으로 정의할 수도 있어요. 이렇게 하면 조건에 따라 스타일을 적용할 수 있죠. 속성이 특정 값을 가지지 않을 때 스타일링할 때 유용해요.

const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          variants: [
            {
              props: (props) =>
                props.variant === 'dashed' && props.color !== 'secondary',
              style: {
                textTransform: 'none',
                border: `2px dashed ${blue[500]}`,
              },
            },
          ],
        },
      },
    },
  },
});

Slot ownerState 콜백 (deprecated)

슬롯의 ownerState에 접근하는 콜백 사용은 deprecated 됐어요. 대신 variants를 사용해 주세요.

 const theme = createTheme({
   components: {
     MuiButton: {
       styleOverrides: {
-        root: ({ ownerState, theme }) => ({ ... }),
+        root: {
+          variants: [...],
         },
       },
     },
   },
 });

sx 문법 (experimental)

sx prop은 테마 객체에 접근하는 커스텀 스타일을 정의하는 단축어 역할을 해요. 이 prop은 CSS의 슈퍼셋을 사용해 인라인 스타일을 작성하게 해 줘요. sx prop의 개념과 sx가 styled 유틸리티와 어떻게 다른지를 더 알아보세요.

sx prop은 styleOverrides 키 안에서도 사용할 수 있어서, 축약형 CSS 표기법으로 테마 안의 스타일을 수정할 수 있어요. 이미 컴포넌트에서 sx prop을 쓰고 있다면 특히 편리한데, 테마에서도 같은 문법을 사용해서 스타일을 빠르게 옮겨 올 수 있거든요.

:::info sx prop은 Material UI v5부터 컴포넌트 커스터마이징에 안정적인 기능이지만, 테마 객체 안에서 직접 사용할 때는 여전히 experimental 로 간주돼요. :::

{{"demo": "GlobalThemeOverrideSx.js", "defaultCodeOpen": false}}
const finalTheme = createTheme({
  components: {
    MuiChip: {
      styleOverrides: {
        root: ({ theme }) =>
          theme.unstable_sx({
            px: 1,
            py: 0.25,
            borderRadius: 1,
          }),
        label: {
          padding: 'initial',
        },
        icon: ({ theme }) =>
          theme.unstable_sx({
            mr: 0.5,
            ml: '-2px',
          }),
      },
    },
  },
});

Specificity

테마 방식으로 컴포넌트를 커스터마이징해도 sx prop은 CSS specificity가 더 높기 때문에 여전히 sx prop으로 오버라이드할 수 있어요. 테마 안에서 experimental sx 문법을 사용했더라도 마찬가지예요.

테마 변수

모든 컴포넌트 인스턴스의 모양을 오버라이드하는 또 다른 방법은 테마 구성 변수(theme configuration variables)를 조정하는 거예요.

const theme = createTheme({
  typography: {
    button: {
      fontSize: '1rem',
    },
  },
});
{{"demo": "ThemeVariables.js"}}

더 알아보기 (Learn more)