In MUI v4, I had bits like this in my JSS classes:
paddingTop: theme.mixins.toolbar.minHeight + theme.spacing(1)
In v5 however, theme.spacing()
returns a string instead of a number. So the above statement would set paddingTop to 568px
, which is 56+'8px'
So what is now the proper way to do math with spacing?
Use the theme. spacing() helper to create consistent spacing between the elements of your UI. MUI uses a recommended 8px scaling factor by default.
To add padding and margin to all React Material-UI components, we can use the Box component. We use Material UI's Box component to add a container with margin and padding. We set the margin on all sides with the m prop and we set the top padding with the pt prop.
The sx prop is a shortcut for defining custom styles that has access to the theme. The sx prop lets you work with a superset of CSS that packages all of the style functions exposed in @mui/system . You can specify any valid CSS using this prop, as well as many theme-aware properties that are unique to MUI System.
MUI Theme
is just an object, you can extend its functionalities from the base theme pretty easily. Once you define and inject your custom theme through ThemeProvider
component, you can start using it anywhere in the children.
The method below create an enhanced version of the original theme with a new method gap(spacing)
that returns the space value in number without the px
unit at the end. You can also use theme.space[index]
to access the value as another alternative:
const createExtendedTheme = () => {
const defaultTheme = createTheme();
const gap = (spacing: number) => parseInt(defaultTheme.spacing(spacing), 10);
return createTheme({
gap,
space: {
0: gap(0),
1: gap(1),
2: gap(2),
3: gap(3),
4: gap(4),
5: gap(5),
},
});
};
// For Typescript users
declare module '@mui/material/styles' {
interface ExtendedTheme {
gap: (spacing: number) => number;
space: {
0: number;
1: number;
2: number;
3: number;
4: number;
5: number;
};
}
interface Theme extends ExtendedTheme {}
interface ThemeOptions extends ExtendedTheme {}
}
const theme = createExtendedTheme();
export default function CustomStyles() {
return (
<ThemeProvider theme={theme}>
<Content />
</ThemeProvider>
);
}
function Content() {
const theme = useTheme();
return (
<Box
sx={{
width: theme.gap(5) * 2,
height: theme.gap(1) + theme.gap(2),
height: theme.space[1] + theme.space[2], // same as above
bgcolor: "tomato"
}}
/>
);
}
`calc(${theme.mixins.toolbar.minHeight} + ${theme.spacing(1)})`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With