Migrating to Pigment CSS
This guide helps you integrate Pigment CSS with Material UI v6.
Before going through this guide, make sure you have upgraded to Material UI v6.
Introduction
The default styling engine of Material UI v6 is Emotion. It lets you write styles in a CSS-in-JS fashion, which is great for dynamic styles that depend on states and props. However, it has some performance drawbacks when it comes to frequent re-renders because the style recalculation happens on the client-side. It also does not fully support React Server Components, a new rendering paradigm that renders components ahead of time on the server.
Pigment CSS aims to solve these problems while keeping the same developer experience of writing styles in a CSS-in-JS fashion. It can work alongside Emotion to ease the migration process, but it is recommended to fully migrate to Pigment CSS in the end.
Supported frameworks
Pigment CSS can be used with one of the following frameworks:
- Next.js App Router with Webpack v5 (Turbopack is not supported yet)
- Vite
Installation
First, install the Material UI wrapper package for Pigment CSS:
npm install @mui/material-pigment-css
Then, follow the instructions based on your framework:
Next.js
Install the Next.js plugin as a dev dependency:
npm install --save-dev @pigment-css/nextjs-plugin
Then, open Next.js config file and add the plugin:
import { withPigment } from '@pigment-css/nextjs-plugin';
const nextConfig = {
// ...Your nextjs config.
};
/**
* @type {import('@pigment-css/nextjs-plugin').PigmentOptions}
*/
const pigmentConfig = {
transformLibraries: ['@mui/material'],
};
export default withPigment(nextConfig, pigmentConfig);
Finally, import the stylesheet at the top of the layout file.
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
+import '@mui/material-pigment-css/styles.css';
export default function RootLayout(props) {
return (
<html lang="en">
<body className={`${inter.className}`}>
{props.children}
</body>
</html>
);
}
Vite
Install the Vite plugin as a dev dependency:
npm install --save-dev @pigment-css/vite-plugin
Next, open the Vite config file (usually named vite.config.mjs
or vite.config.js
) and add the plugin:
import { defineConfig } from 'vite';
import { pigment } from '@pigment-css/vite-plugin';
/**
* @type {import('@pigment-css/vite-plugin').PigmentOptions}
*/
const pigmentConfig = {
transformLibraries: ['@mui/material'],
};
export default defineConfig({
plugins: [
pigment(pigmentConfig),
// ... Your other plugins.
],
});
Finally, add the Pigment CSS stylesheet to the top of the main file.
import * as React from 'react';
+import '@mui/material-pigment-css/styles.css';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
Configuring the theme
Integrating Pigment CSS with Material UI requires you to configure the theme to the plugin. Add the following code to your Next.js or Vite config file:
+import { createTheme } from '@mui/material';
const pigmentConfig = {
transformLibraries: ['@mui/material'],
+ theme: createTheme({
+ cssVariables: true,
+ /* other parameters, if any */
+ }),
};
If you have a custom theme, follow the theme migration instructions next. Otherwise you're now ready to start the development server:
npm run dev
Open the browser and navigate to the localhost URL, you should see the app running with Pigment CSS.
Next.js font optimization
If you are using next/font
to optimize font loading, pass a CSS variable name to the variable
property of the font configuration and use it in the body className:
import { Roboto } from 'next/font/google';
const roboto = Roboto({
weight: ['300', '400', '500', '700'],
subsets: ['latin'],
display: 'swap',
+ variable: '--my-font-family',
});
export default function RootLayout(props) {
const { children } = props;
return (
<html lang="en">
+ <body className={roboto.variable}>
{children}
</body>
</html>
);
}
Finally, update the typography.fontFamily
value with the variable created in the previous step:
const pigmentConfig = {
transformLibraries: ['@mui/material'],
theme: createTheme({
+ typography: {
+ fontFamily: 'var(--my-font-family)',
+ },
}),
};
TypeScript
If you are using TypeScript, you need to extend the Pigment CSS theme types with Material UI Theme
.
Add the following code to a file that is included in your tsconfig.json
:
// e.g. App.tsx
import { Theme } from '@mui/material/styles';
declare module '@mui/material-pigment-css' {
interface ThemeArgs {
theme: Theme;
}
}
Then, verify that the types is correctly picked up by Pigment CSS with the following code:
// e.g. App.tsx
import { styled } from '@mui/material-pigment-css';
const TestThemeTypes = styled('div')(({ theme }) => ({
color: theme.palette.primary.main,
}));
You should see no TypeScript errors in your editor. Finally, remove the test code.
How it works
When a Pigment CSS plugin is configured through a framework bundler, it intercepts the styling APIs that Material UI uses and replaces them with those from Pigment CSS instead. Pigment CSS then extracts the styles at build time and injects them into the stylesheet.
If you come from Material UI v5, using Pigment CSS will be a paradigm shift in terms of writing styles. Since Pigment CSS is a build-time extraction tool, it does not support dynamic styles that depend on runtime variables. For example, Pigment CSS will throw an error for styles that depend on a state like the one below:
import Card from '@mui/material/Card';
function App() {
const [color, setColor] = useState('#000000');
return (
<Card
sx={{
color, // ❌ Pigment CSS cannot extract this style.
}}
/>
);
}
We recommend reading the rest of the guide below to learn about the new styling paradigm and patterns for creating dynamic styles.
Migrating custom theme
Removing owner state
Since Pigment CSS is a build-time extraction tool, it does not support owner state through callbacks. Here is an example that will throw an error at build time:
const theme = createTheme({
components: {
MuiCard: {
styleOverrides: {
root: {
color: ({ ownerState }) => ({
// ❌ Pigment CSS cannot extract this style.
...(ownerState.variant === 'outlined' && {
borderWidth: 3,
}),
}),
},
},
},
},
});
Run the following codemod to remove the owner state from the theme:
npx @mui/codemod@latest v6.0.0/theme-v6 next.config.mjs
There are cases where the codemod is not able to remove the owner state. In such cases, you have to manually replace the owner state with variants
.
Dynamic color based on palette
If you have a dynamic color based on the theme palette, you can use the variants
property to define the styles for each palette.
const theme = createTheme({
components: {
MuiCard: {
styleOverrides: {
root: ({ theme, ownerState }) => ({
color: theme.palette[ownerState.palette]?.main,
}),
},
},
},
});
Default props provider
Use DefaultPropsProvider
in your main application file and move all the component default props to it:
import { createTheme } from '@mui/material';
const customTheme = createTheme({
// ...other tokens.
components: {
MuiButtonBase: {
- defaultProps: {
- disableRipple: true,
- },
},
MuiSelect: {
- defaultProps: {
- IconComponent: DropdownIcon,
- },
}
}
});
Migrating dynamic styles
sx prop
Run the following codemod:
npx @mui/codemod@latest v6.0.0/sx-prop path/to/folder
The scenarios below are not covered by the codemod, so you have to manually update them:
Dynamic values
If a value depends on a variable, you need to move it to a CSS variable inside inline styles.
<div>
{items.map((item, index) => (
<Box
key={index}
sx={{
borderRadius: '50%',
width: `max(${6 - index}px, 3px)`,
height: `max(${6 - index}px, 3px)`,
bgcolor: index === 0 ? 'primary.solidBg' : 'background.level3',
}}
/>
))}
</div>
Custom components
With Pigment CSS, any JSX element can accept the sx
prop so it is no longer needed to pass down the sx
prop to Material UI components.
import ButtonBase from '@mui/material/ButtonBase';
function ActiveButton({ sx, ...props }) {
return (
<ButtonBase
sx={[
{
'&:active': {
opacity: 0.5,
},
},
- ...Array.isArray(sx) ? sx : [sx],
]}
{...props}
/>
);
}
styled
If you have custom components that are using styled
from @mui/material/styles
, change the import source to @mui/material-pigment-css
:
-import { styled } from '@mui/material/styles';
+import { styled } from '@mui/material-pigment-css';
Then, run the following codemod:
npx @mui/codemod@latest v6.0.0/styled path/to/folder
The scenarios below are not covered by the codemod, so you have to manually update them:
Dynamic styles based on props
If you have dynamic styles based on props, you need to move them to CSS variables. You will need to create a wrapper component to set the inline style with the CSS variables.
const FlashCode = styled('div')(
({ theme, startLine = 0, endLine = startLine, lineHeight = '0.75rem' }) => ({
top: `calc(${lineHeight} * 1.5 * ${startLine})`,
height: `calc(${lineHeight} * 1.5 * ${endLine - startLine + 1})`,
...theme.typography.caption,
}),
);
export default FlashCode;
Migrating layout components
To use layout components that are compatible with Pigment CSS, replace the following components with those from the adapter package:
-import Container from '@mui/material/Container';
+import Container from '@mui/material-pigment-css/Container';
-import Grid from '@mui/material/Grid';
+import Grid from '@mui/material-pigment-css/Grid';
-import Stack from '@mui/material/Stack';
+import Stack from '@mui/material-pigment-css/Stack';
-import Hidden from '@mui/material/Hidden';
+import Hidden from '@mui/material-pigment-css/Hidden';
Migrating Box component
Choose one of the following approaches:
Continue using Box
Replace the Box
component with the one from the adapter package:
-import Box from '@mui/material/Box';
+import Box from '@mui/material-pigment-css/Box';
Use HTML element
Pigment CSS can extract the sx
prop from any JSX element, so there is no need to use the Box component.
-import Box from '@mui/material/Box';
function CustomCard() {
return (
- <Box sx={{ display: 'flex' }}>
- <Box component="img" src="..." sx={{ width: 24, height: 24 }}>
- ...
- </Box>
+ <div sx={{ display: 'flex' }}>
+ <img src="..." sx={{ width: 24, height: 24 }}>
+ ...
+ </div>
);
}
For TypeScript users, you need to extend the HTMLAttributes
interface to support the sx
prop. Add the following code to a file that is included in your tsconfig.json
:
import type { Theme, SxProps } from '@mui/material/styles';
declare global {
namespace React {
interface HTMLAttributes<T> {
sx?: SxProps<Theme>;
}
interface SVGProps<T> {
sx?: SxProps<Theme>;
}
}
}
Migrate useTheme hook
If you are using the useTheme
hook, replace the import source:
-import { useTheme } from '@mui/material/styles';
+import { useTheme } from '@mui/material-pigment-css';
Right-to-left support
Update the config file with the following code to enable right-to-left support:
const pigmentConfig = {
theme: createTheme(),
+ css: {
+ // Specify your default CSS authoring direction
+ defaultDirection: 'ltr',
+ // Generate CSS for the opposite of the `defaultDirection`
+ // This is set to `false` by default
+ generateForBothDir: true,
+ },
}
Migrating from theme direction
If you are using the theme.direction
in your component, wrap your application with RtlProvider
and use the useRtl
hook to get the direction instead:
+ import RtlProvider from '@mui/material-pigment-css/RtlProvider';
function App() {
+ const [rtl, setRtl] = React.useState(false);
return (
+ <RtlProvider value={rtl}>
{/* Your app */}
+ </RtlProvider>
)
}