When using Styled Components with MUI System Props I found that the styled component styling takes precedence, for example in the snippet below the box would render with justify content
set as space-around
:
const CustomBox = styled(Box)(() => ({
display: 'flex',
justifiyContent: 'center'
}));
function MyComponent() (
<CustomBox justifyContent='space-around'>
<span className='some-icon'></span>
<span>some text</span>
</CustomBox>
)
I could manage this "the styled components way" and pass a prop to CustomBox
, but I find it counter-intuitive that the MIUI system prop looks like a local override, but is overriden by the component it’s being applied to.
Is there some configuration available in MUI that would make MUI System Props take precedence over Styled Components stylings?
2
Answers
The styles attached with
styled
is overridden by thesx
prop on the component. Usually this can be used to add any additional local styles to astyled
component with MUI.Unless specified to disable it,
styled
also add support for thesx
prop by default if used with a base JSX component such asdiv
, for quick style overrides.More examples on a demo: stackblitz
If you want the props passed to the
CustomBox
to win over your style overrides, then you should take the props into account in your styling:As far as why the props don’t automatically take precedence — the props change the default styling for the
Box
and that default styling is what thestyled
API is then overriding. Since thestyled
API gives you access to those props, it allows you to decide how those props interact with your styling.In contrast, the
sx
prop provides styles that are applied with a different precedence than the default styles, so providingjustifyContent
withinsx
wins over both the props and styles provided viastyled
.