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

ClassName generator

원문 보기 위키 갱신

빌드 시점에 클래스명 생성을 구성할 수 있는 API예요.

출처: 문서

본문

이 API는 deprecated 된 createGenerateClassName을 대체하기 위해 @mui/material (v5.0.5)에 도입됐어요.

:::warning 이 API는 불안정한 단계에 있으며 미래에 변경될 수 있어요. :::

설정

기본적으로 Material UI는 각 컴포넌트 슬롯에 전역 클래스명을 생성해요. 예를 들어 <Button>Text</Button>은 다음과 같은 HTML을 생성해요.

<button
  class="MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeMedium MuiButton-textSizeMedium MuiButtonBase-root css-1ujsas3"
>
  Text
</button>

Material UI 컴포넌트가 생성하는 모든 클래스명을 커스터마이즈하려면 별도의 JavaScript 파일을 만들어 ClassNameGenerator API를 사용하세요.

// create a new file called `MuiClassNameSetup.js` at the root or src folder.
import { unstable_ClassNameGenerator as ClassNameGenerator } from '@mui/material/className';

ClassNameGenerator.configure(
  // Do something with the componentName
  (componentName) => componentName,
);

그리고 index의 루트에서 어떤 @mui/* 임포트보다 먼저 이 파일을 임포트해 주세요.

import './MuiClassNameSetup';
import Button from '@mui/material/Button';
// ...other component imports

function App() {
  return <Button>Text</Button>;
}

구성 예시들은 다음과 같아요.

클래스명 접두사 바꾸기

// MuiClassNameSetup.js
import { unstable_ClassNameGenerator as ClassNameGenerator } from '@mui/material/className';

ClassNameGenerator.configure((componentName) => `foo-bar-${componentName}`);

그 결과 HTML이 다음과 같이 바뀌어요.

<button
  class="foo-bar-MuiButton-root foo-bar-MuiButton-text foo-bar-MuiButton-textPrimary foo-bar-MuiButton-sizeMedium foo-bar-MuiButton-textSizeMedium foo-bar-MuiButtonBase-root css-1ujsas3"
>
  Button
</button>

컴포넌트 클래스명 이름 바꾸기

모든 Material UI 컴포넌트는 ${componentName}-${slot} 클래스명 형식을 가져요. 예를 들어 Chip의 컴포넌트 이름은 MuiChip으로, 모든 <Chip /> 요소의 전역 클래스명으로 사용돼요. Mui 접두사를 다음과 같이 제거하거나 바꿀 수 있어요.

// MuiClassNameSetup.js
import { unstable_ClassNameGenerator as ClassNameGenerator } from '@mui/material/className';

ClassNameGenerator.configure((componentName) => componentName.replace('Mui', ''));

이제 Mui 클래스는 사라져요.

<div
  class="Chip-root Chip-filled Chip-sizeMedium Chip-colorDefault Chip-filledDefault css-mttbc0"
>
  Chip
</div>

:::warning 상태 클래스(State classes)는 컴포넌트 이름이 아니므로 변경하거나 제거할 수 없어요. :::

주의사항

  • ClassNameGenerator.configure는 어떤 Material UI 컴포넌트를 임포트하기 전에 호출해야 해요.

  • 테마/커스터마이징을 할 때는 올바른 생성 클래스명을 얻기 위해 항상 [component]Classes를 사용해야 해요.

    +import { outlinedInputClasses } from '@mui/material/OutlinedInput';
    
     const theme = createTheme({
       components: {
         MuiOutlinedInput: {
           styleOverrides: {
             root: {
    -          '& .MuiOutlinedInput-notchedOutline': {
    +          // the result will contain the prefix.
    +          [`& .${outlinedInputClasses.notchedOutline}`]: {
                 borderWidth: 1,
               }
             }
           }
         }
       }
     });
    
  • 이 API는 빌드 시점(build-time)에만 사용해야 해요.

  • 구성은 앱 전체의 모든 컴포넌트에 적용돼요. 앱의 특정 부분만 대상으로 할 수는 없어요.

프레임워크 예시

ClassNameGenerator 호출을 항상 맨 위로 끌어올리도록 초기화 파일을 만드세요.

// create a new file called `MuiClassNameSetup.js` at the root or src folder.
'use client'; // remove this line if you are not using React Server Components
import { unstable_ClassNameGenerator as ClassNameGenerator } from '@mui/material/className';

ClassNameGenerator.configure(
  // Do something with the componentName
  (componentName) => componentName,
);

export default null;

그런 다음 프레임워크에 따라 메인 JavaScript 소스에서 이 파일을 임포트해 주세요.

Next.js App Router

/app/page.js에 'use client' 지시어를 추가하고 초기화 파일을 임포트해 주세요.

+'use client';
+import './MuiClassNameSetup';
 import * as React from 'react';
 import Button from '@mui/material/Button';

 export default function Page() {
   return (
     <Button>Text</Button>
   );
 }

Next.js Pages Router

/pages/_app.js에 초기화 파일을 임포트해 주세요.

+import './MuiClassNameSetup';
 import * as React from 'react';
 import PropTypes from 'prop-types';
 import Head from 'next/head';

 export default function MyApp(props) {
   const { Component, pageProps } = props;

   return (
     <Component {...pageProps} />
   );
 }

Create React App

/src/index.js에 초기화 파일을 임포트해 주세요.

+import './MuiClassNameSetup';
 import * as React from 'react';
 import * as ReactDOM from 'react-dom';
 import App from './App';

 ReactDOM.render(<App />);

더 알아보기 (Learn more)