Prevent All Props Being Passed Down By Styled Components

Styled Components pass all props on by design, this allows us to wrap components in a styled component without altering their behaviour. However sometimes you don’t want all props to be passed through the styled component when you simply need a prop for styling logic but not component behaviour.

If a prop which is not a valid HTML attribute is passed all the way through the component hierarchy to a native DOM element then React will warn about the unknown prop on that element.

For example, assume we have a Header component which passes on all props to a <h2>:

const Header = props => <h2 {...props}>Some Text</h2>;

If we wish to alter its background colour depending on a prop we may have something which looks like this:

const StyledHeader = styled(Header)`
  background-color: ${ props => props.myProp ? 'green' : 'red' };

myProp will be passed down through Header and react will attempt to apply it to the <h2> element that Header renders.

To avoid this, the prop we do not wish to pass through can be filtered by means of destructuring and use of the rest operator.

const FilteredHeader = ({myProp, ...otherProps}) => <Header {...otherProps} />;

const StyledHeader = styled(FilteredHeader)`
  background-color: ${ props => props.myProp ? 'green' : 'red' };
React Styled Components