Styling Third-Party Components with `Styled-Components`

I ran into this issue today while trying to use the godsend to React styling libraries: https://www.styled-components.com. I just wanted to use a Row element from Ant-Design, and give it prop for adding an active class. Pretty easy to do with class names, but I wanted to use SC.

The difficulty came when attaching an unknown prop to the 3rd party component:

In the React ecosystems, declaring Prop-Types allows for a semi-strict means of checking the data types of a component’s properties (passed in whenever a component is created). However, as of React v15 (I think), these prop-types must be defined, otherwise you’ll get some not-so-nice errors.

Solution: use data-<propName>

Alternatively: someone posted a workaround utility function which you could use, but I would claim that the first method is a bit cleaner. Here’s that code:

const swallowingStyled = (WrappedComponent, {swallowProps = []} = {}) => {
const Wrapper = ({children, ...props}) => {
swallowProps.forEach(propName => {
delete props[propName];
});
return <WrappedComponent {...props}>{children}</WrappedComponent>;
};
return styled(Wrapper);
};

which can be used like so:

const Card = swallowingStyled(Paper, {swallowProps: ['samplesMode']})`
margin: 0 10px 10px 0;
padding: 10px;
flex-flow: ${({samplesMode}) => samplesMode && 'column'};
`;

More links: