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

테마 컴포넌트

원문 보기 위키 갱신

테마 컴포넌트 (Themed components)

테마 안의 컴포넌트 키(component key)를 사용해서 컴포넌트의 스타일, 기본 props 등을 커스터마이즈하는 방법을 알아봐요. 전역적으로 여러 컴포넌트의 스타일을 한 번에 잡고 싶을 때 테마의 components 키가 큰 역할을 한답니다.

출처: 문서

본문

컴포넌트 키를 테마 안에서 사용하면 컴포넌트의 스타일, 기본 props 등을 커스터마이즈할 수 있어요.

테마 안의 components 키는 애플리케이션 전체에 걸쳐 스타일 일관성을 달성하는 데 도움을 줘요. 다만 테마는 tree-shakable하지 않으므로, 무거운(heavy) 커스터마이즈의 경우에는 새 컴포넌트를 만드는 쪽을 선호하세요.

테마 기본 props (Theme default 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 💣!
      },
    },
  },
});
import { createTheme, ThemeProvider } from '@mui/material/styles';
import Button from '@mui/material/Button';

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

export default function DefaultProps() {
  return (
    <ThemeProvider theme={theme}>
      <Button>This button has disabled ripples.</Button>
    </ThemeProvider>
  );
}

TypeScript와 lab 컴포넌트를 사용한다면, 이 글에서 스타일을 재정의하는 방법을 확인하세요.

테마 스타일 재정의 (Theme style overrides)

테마의 styleOverrides 키를 사용하면 Material UI 컴포넌트의 기본 스타일을 변경할 수 있어요.

styleOverrides는 키로 슬롯 이름을 필요로 하며(가장 바깥 요소를 타겟팅하려면 root를 사용), 값으로는 CSS 속성 객체를 넣어요. 중첩된 CSS 선택자도 값으로 지원됩니다.

const theme = createTheme({
  components: {
    // Name of the component
    MuiButton: {
      styleOverrides: {
        // Name of the slot
        root: {
          // Some CSS
          fontSize: '1rem',
        },
      },
    },
  },
});
import { ThemeProvider, createTheme } from '@mui/material/styles';
import Button from '@mui/material/Button';

const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          fontSize: '1rem',
        },
      },
    },
  },
});

export default function GlobalThemeOverride() {
  return (
    <ThemeProvider theme={theme}>
      <Button>font-size: 1rem</Button>
    </ThemeProvider>
  );
}

변형 (Variants)

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

특정 prop을 기준으로 스타일을 재정의하고 싶다면, props와 style 키를 포함하는 특정 슬롯의 variants 키를 사용할 수 있어요. 컴포넌트의 props가 일치하면 style이 적용됩니다.

재정의 정의는 배열(array)로 지정해요. 또한 우선순위를 가져야 할 스타일은 마지막에 나열되도록 하세요.

기존 props에 기반한 스타일 재정의 (Overriding styles based on existing props)

아래 예제는 outlined Card의 테두리 두께를 증가시키는 방법을 보여줘요:

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

새 값에 기반한 스타일 추가 (Adding styles based on new values)

아래 예제는 Button 컴포넌트에 새로운 변형 dashed를 추가하는 방법을 보여줘요:

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]}`,
              },
            },
          ],
        },
      },
    },
  },
});

기존 props와 새 props에 기반한 스타일 재정의 (Overriding styles based on existing and new props)

아래 예제는 Button의 변형이 dashed(새 변형)이고 color가 secondary(기존 색)일 때 스타일을 재정의하는 방법을 보여줘요:

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

TypeScript를 사용한다면 모듈 증강(module augmentation)을 통해 새 변형/색상을 지정해야 해요.

declare module '@mui/material/Button' {
  interface ButtonPropsVariantOverrides {
    dashed: true;
  }
}
import { createTheme, ThemeProvider } from '@mui/material/styles';
import Button from '@mui/material/Button';

declare module '@mui/material/Button' {
  interface ButtonPropsVariantOverrides {
    dashed: true;
  }
}

const customTheme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          variants: [
            {
              props: { variant: 'dashed' },
              style: ({ theme }) => ({
                textTransform: 'none',
                border: `2px dashed ${theme.palette.primary.main}`,
                color: theme.palette.primary.main,
              }),
            },
            {
              props: { variant: 'dashed', color: 'secondary' },
              style: ({ theme }) => ({
                border: `2px dashed ${theme.palette.secondary.main}`,
                color: theme.palette.secondary.main,
              }),
            },
            {
              props: { variant: 'dashed', size: 'large' },
              style: {
                borderWidth: 4,
              },
            },
            {
              props: { variant: 'dashed', color: 'secondary', size: 'large' },
              style: {
                fontSize: 18,
              },
            },
          ],
        },
      },
    },
  },
});

export default function GlobalThemeVariants() {
  return (
    <ThemeProvider theme={customTheme}>
      <Button variant="dashed" sx={{ m: 1 }}>
        Dashed
      </Button>
      <Button variant="dashed" color="secondary" sx={{ m: 1 }}>
        Secondary
      </Button>
      <Button variant="dashed" size="large" sx={{ m: 1 }}>
        Large
      </Button>
      <Button variant="dashed" color="secondary" size="large" sx={{ m: 1 }}>
        Secondary large
      </Button>
    </ThemeProvider>
  );
}

변형 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 문법 (실험적) (The sx syntax (experimental))

sx prop은 테마 객체에 접근하는 커스텀 스타일을 정의하는 단축어(shorthand) 역할을 해요. 이 prop을 사용하면 CSS의 상위 집합(superset)으로 인라인 스타일을 작성할 수 있어요. sx prop 뒤에 숨은 개념과 sx가 styled 유틸리티와 어떻게 다른지에 대해 자세히 알아보세요.

테마 안에서 styleOverrides 키 내부에 sx prop을 사용하면, 축약 CSS 표기법(shorthand CSS notation)으로 스타일을 수정할 수 있어요. 이미 컴포넌트에 sx prop을 쓰고 있다면 특히 유용한데, 테마에서도 같은 문법을 사용할 수 있고 두 곳 사이에서 스타일을 빠르게 전송할 수 있거든요.

:::info sx prop은 Material UI v5부터 컴포넌트 커스터마이즈를 위한 안정적인(stable) 기능이지만, 테마 객체 안에서 직접 사용할 때는 여전히 실험적(experimental) 으로 간주됩니다. :::

import { ThemeProvider, createTheme } from '@mui/material/styles';
import Chip from '@mui/material/Chip';
import Check from '@mui/icons-material/Check';

const finalTheme = createTheme({
  components: {
    MuiChip: {
      styleOverrides: {
        root: ({ theme }) =>
          theme.unstable_sx({
            // https://mui.com/system/getting-started/the-sx-prop/#spacing
            px: 1,
            py: 0.25,
            // https://mui.com/system/borders/#border-radius
            borderRadius: 1, // 4px as default.
          }),
        label: {
          padding: 'initial',
        },
        icon: ({ theme }) =>
          theme.unstable_sx({
            mr: 0.5,
            ml: '-2px',
          }),
      },
    },
  },
});

export default function GlobalThemeOverrideSx() {
  return (
    <ThemeProvider theme={finalTheme}>
      <Chip
        color="success"
        label={
          <span>
            <b>Status:</b> Completed
          </span>
        }
        icon={<Check fontSize="small" />}
      />
    </ThemeProvider>
  );
}

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으로 재정의할 수 있어요. 설령 테마 안에서 실험적인 sx 문법을 사용하고 있더라도 말이죠.

테마 변수 (Theme variables)

모든 컴포넌트 인스턴스의 외형을 재정의하는 또 다른 방법은 테마 구성 변수를 조정하는 것이에요.

const theme = createTheme({
  typography: {
    button: {
      fontSize: '1rem',
    },
  },
});
import { ThemeProvider, createTheme } from '@mui/material/styles';
import Button from '@mui/material/Button';

const theme = createTheme({
  typography: {
    button: {
      fontSize: '1rem',
    },
  },
});

export default function ThemeVariables() {
  return (
    <ThemeProvider theme={theme}>
      <Button>font-size: 1rem</Button>
    </ThemeProvider>
  );
}

더 알아보기 (Learn more)