Destructuring props in styled-components

Posted on

One of the neat features of styled-components is how we can use props to adjust styles. If we use them as outlined in this article, we can make working with props a bit more convenient.

Imagine we’re working on a blog that has a lot of posts. To highlight our best articles, we want to mark them as “featured”. One way to do this in React is by having two separate components called <Post> and <FeaturedPost>.

<Post>
  This is a regular post.
</Post>
 
<FeaturedPost>
  This is a featured post!
</FeaturedPost>
<Post>
  This is a regular post.
</Post>
 
<FeaturedPost>
  This is a featured post!
</FeaturedPost>

This could lead to a lot of duplication since much of the code would be identical across both components. styled-components let us pass an isFeatured property to the regular <Post> component instead:

<Post>
  This is a regular post.
</Post>
 
<Post isFeatured>
  This is a featured post!
</Post>
<Post>
  This is a regular post.
</Post>
 
<Post isFeatured>
  This is a featured post!
</Post>

We can then use props.isFeatured in our styled-component to switch between styles:

const Post = styled.article`
  background: ${props =>
    props.isFeatured ? props.theme.yellow : props.theme.white
  };
`
const Post = styled.article`
  background: ${props =>
    props.isFeatured ? props.theme.yellow : props.theme.white
  };
`

In this example, we have to write props. three times. This becomes more tedious as we pass more properties and change more styles. We can destructure the passed props to reduce the number of times we have to type props..

const Post = styled.article`
  background: ${({ isFeatured, theme }) =>
    isFeatured ? theme.yellow : theme.white
  };
`;
const Post = styled.article`
  background: ${({ isFeatured, theme }) =>
    isFeatured ? theme.yellow : theme.white
  };
`;

To improve this even further, we can use a single arrow function in our styled-components.

Debug
none
Grid overlay