Pular para o conteúdo

ClassName Generator

Configure classname generation at build time.

This API is introduced in @mui/material (v5.0.5) as a replacement of deprecated createGenerateClassName.

⚠️ Note: this API is at an unstable stage which might change in the future.

Global classname prefix

By default, MUI generates a global classname for each component slot. For example:

import Button from '@mui/material/Button';

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

Generates the following HTML:

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

To add prefix to all class names generated by the MUI components, pass a callback to ClassNameGenerator.configure(callback).

import { unstable_ClassNameGenerator as ClassNameGenerator } from '@mui/material/utils';

// call this function at the root of the application
ClassNameGenerator.configure((componentName) => `foo-bar-${componentName}`);

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

As a result, the HTML result changes to the following:

<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>

Component renaming

Every MUI component has ${componentName}-${slot} classname format. For example, the component name of Chip is MuiChip, which is used as a global class name for every <Chip /> element. You can remove/change the Mui prefix as follows:

import { unstable_ClassNameGenerator } from '@mui/material/utils';

// call this function at the root of the application
unstable_ClassNameGenerator.configure((componentName) =>
  componentName.replace('Mui', ''),
);

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

Now, the Mui class is gone.

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

Note: state classes are NOT component names and therefore cannot be changed/removed.

Caveat

  • you should always use [component]Classes for theming/customization to get the correct generated class name.

    +import { outlinedInputClasses } from '@mui/material/OutlinedInput';
    
    const theme = createTheme({
      components: {
        MuiOutlinedInput: {
          styleOverrides: {
            root: {
    -         '& .MuiOutlinedInput-notchedOutline': {
    +         [`& .${outlinedInputClasses.notchedOutline}`]: { // the result will contain the prefix.
                borderWidth: 1,
              }
            }
          }
        }
      }
    });
    
  • This API should only be used at build-time.

  • The configuration is applied to all of the components across the application. You cannot target a specific part of the application.