Reputation: 29
const MyThemeComponent = styled('div', {
// Configure which props should be forwarded on DOM
shouldForwardProp: (prop) =>
prop !== 'color' && prop !== 'variant' && prop !== 'sx',
name: 'MyThemeComponent',
slot: 'Root',
// We are specifying here how the styleOverrides are being applied based on props
overridesResolver: (props, styles) => [
styles.root,
props.color === 'primary' && styles.primary,
props.color === 'secondary' && styles.secondary,
],
})(({ theme }) => ({
backgroundColor: 'aliceblue',
padding: theme.spacing(1),
}));
Anyone can explain what shouldForwardProp does? Actually i'm struggling to understand this piece of code
shouldForwardProp: (prop) =>
prop !== 'color' && prop !== 'variant' && prop !== 'sx',
Upvotes: 2
Views: 2713
Reputation: 13357
In a nutshell it's asking "Do you want the color
, variant
, and sx
props that you set on instances of <MyThemeComponent />
to also be set on the underlying div
element that you're styling?".
In this case, the answer is probably "no" because those three props are not valid attributes on a div
. Since a styled
component "forwards" any props that are passed to it to its underlying element/component by default, the shouldForwardProps
function lets you filter the ones out that you don't want passed. In this case the shouldForwardProps
functions says "if the props passed to me are NOT color
, variant
, or sx
, then ("yes") put them as attributes on the div
."
In this example image, you can see that I commented out your prop !== color
line and the color
props was passed to the underlying div
, as an attribute, while variant
and sx
are not being passed:
Upvotes: 5