styled-component .attrs - React does not recognize prop
To prevent components that pass all props to a DOM element, create a wrap of your component but do not pass your custom props to the children component via "Object destructuring". In this way, you can style the wrapped component and styled-components
can access to the prop but the children will not have custom properties, and your warning will disappear.
import React from 'react';
import styled from 'styled-components';
import Typography from '@material-ui/core/Typography'
const WrappedTypography = ({ maxWidth, ...props }) => {
return <Typography {...props} />
}
const Text = styled(WrappedTypography) `
${({ maxWidth }) => maxWidth ? `max-width: ${maxWidth}` : null}
`
export default Text;
You can learn more about deestructuring at Mozilla docs.
Update: Use transient props
With the release 5.1.0 you can use transient props
. This way you do not need an extra wrapper i.e. unnecessary code is reduced:
Transient props are a new pattern to pass props that are explicitly consumed only by styled components and are not meant to be passed down to deeper component layers. Here's how you use them:
const Comp = styled.div`
color: ${props => props.$fg || 'black'};
`;
render(<Comp $fg="red">I'm red!</Comp>);
Note the dollar sign ($) prefix on the prop; this marks it as transient and styled-components knows not to add it to the rendered DOM element or pass it further down the component hierarchy.
The new answer should be:
Component:
<ImageWithText
$imageData={data.headerBackgroundImage.childImageSharp.fluid} // notice the '$'
minHeight='50vh'>
Declaration of styled component:
const StyledBackgroundImage = styled(BackgroundImage).attrs(({$minHeight}) => ({
minHeight: minHeight || "60vh",
}))`
min-height: ${({$minHeight}) => $minHeight}; // notice the '$' before the prop name
/* ... */
`;