I was able to put together that shouldForwardProp
specifies which props should be forwarded to the wrapped element passed as an option to styled()
, but I am having trouble finding a comprehensible example of its use case.
Is prop forwarding here akin to passing down props in React?
Why would one want to prevent certain props from being forwarded to the wrapped element while using styled()
?
Forgive me for my ignorance or if my question lacks clarity - I am still learning MUI and attempting to wrap my head around it.
CodePudding user response:
If you're using a built-in components like div
or span
and you want to allow the user to customize the styles via some props.
const MyComponent = styled('div')(({ bgColor }) => ({
backgroundColor: bgColor,
}));
When you're using it like this:
<MyComponent bgColor='red'>
The prop is passed to the real element in the DOM tree as attribute:
And react will complain, something like:
Warning: React does not recognize the `bgColor` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `bgcolor` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
This is why shouldForwardProp
exists, to prevent styling props from being passed down and create invalid attribute:
const MyComponent = styled('div', {
shouldForwardProp: (props) => props !== 'bgColor',
})(({ bgColor }) => ({
backgroundColor: bgColor,
}));