Home > Blockchain >  How To correctly Apply the Box component spacing props?
How To correctly Apply the Box component spacing props?

Time:10-19

Adding margins and spacing can be done easily. Material-UI gave us some shortcuts for this. Instead of CSS styling each component.

In the following line of code, The margin does not apply correctly without specifying the px measurement unit

 <Box display="flex" alignItems="center" marginRight={`${theme.spacing(25)}px`}>...</Box>

I'm trying to let MUI do the work, and leverage the technology as opposed to using CSS classes for styling.

However, it's more convenient to use it without string's concatenation

 <Box display="flex" alignItems="center" marginRight={theme.spacing(25)}>...</Box>

CodePudding user response:

Looking at docs (https://mui.com/components/box/), you should not use theme object in any way.

<Box display="flex" alignItems="center" marginRight={2}>...</Box>

Value 2 will be passed to theme.spacing() for you and px suffix will be added as well. Tested on v4.10.

PS. Not using theme means that you don't have to call useTheme() as well.

EDIT

I think I have found a possible reason of your problem. Look at this: https://github.com/mui-org/material-ui/blob/a0e725d119bbb91fb4f8cd6b44745916e66c2e2e/packages/mui-system/src/createTheme/createSpacing.ts#L29

If you are using mui v5, you might see message in the console (https://github.com/mui-org/material-ui/blob/a0e725d119bbb91fb4f8cd6b44745916e66c2e2e/packages/mui-system/src/spacing.js#L130).

It seems that valid values passed to margin prop is from range 0-8, but you passed 25 (I never used value that high).

Please be aware that 1 does not mean 1px, the return value may vary, but it is 8px by default.

  • Related