Skip to content
+

Configure the sx prop

Learn about the experimental API for extending or changing the behavior of the sx prop.

Extend the sx prop

You can add new keys to be processed by the sx prop by extending the unstable_sxConfig option inside the theme, as shown below:

import { Box, handleBreakpoints } from '@mui/system';
import { createTheme, ThemeProvider } from '@mui/material/styles';

const customTheme = createTheme({
  unstable_sxConfig: {
    size: {
      style: (props) => {
        const { size, theme } = props;

        const styleFromPropValue = (propValueFinal: number) => {
          const value = theme.spacing(propValueFinal);

          return {
            width: value,
            height: value,
          };
        };

        // Adding support for the breakpoints syntax
        return handleBreakpoints(props, size, styleFromPropValue);
      },
    },
  },
});

export default function ExtendTheSxProp() {
  return (
    <ThemeProvider theme={customTheme}>
      <Box sx={{ size: 10, border: 1 }} />
    </ThemeProvider>
  );
}

Override existing behavior

It is also possible to change some of the existing behavior of the sx prop. For example, in some design systems, the border radiuses need to be restricted to specific values, instead of allowing any number to be used—as is the default with MUI System. You can change this behavior by providing a custom config for the borderRadius property:

import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import { createTheme, ThemeProvider } from '@mui/material/styles';

// Retain type safety.
declare module '@mui/system' {
  interface Shape {
    sm: number;
    md: number;
    lg: number;
  }
}

const theme = createTheme({
  unstable_sxConfig: {
    // You can now use the borderRadius key in sx
    // by providing direct values from the palette
    borderRadius: {
      themeKey: 'shape',
    },
  },
  shape: {
    sm: 4,
    md: 8,
    lg: 12,
  },
});

export default function ChangeTheBehaviorSxProp() {
  return (
    <Stack direction="row" sx={{ gap: 1 }}>
      <ThemeProvider theme={theme}>
        <Box sx={{ borderRadius: 'sm', border: 1, p: 4 }} />
        <Box sx={{ borderRadius: 'md', border: 1, p: 4 }} />
        <Box sx={{ borderRadius: 'lg', border: 1, p: 4 }} />
      </ThemeProvider>
    </Stack>
  );
}

API

Each value of the config inside unstable_sxConfig accepts the following properties:

  • cssProperty (string [optional]): Indicates the CSS property, if it is different than the key
  • themeKey (string [optional]): The path of the theme mapping
  • transform ((cssValue: unknown, userValue: unknown) => number | string | React.CSSProperties | CSSObject [optional]): Lets users define a function that can transform the value before it's returned
  • style ((props: any) => CSSObject [optional]): Offers maximum customizability. Note that you need to make sure that the breakpoint values can be processed