I recently discovered an incredibly useful feature in Styled Components that allows sharing blocks of CSS properties between components. Here’s a simple example where I create a variable called
sharedProps that is passed into two different components,
One thing that I have always found clunky in CSS is creating responsive breakpoints using
@media queries. Let’s look at an example.
Here I have used
@media queries to change
margin with regard to screen breakpoints.
Now let’s write a function that can utilize what we’ve learnt about sharing code in Styled Components and generate these media queries. We want the function to take in arguments for:
- The CSS property to which we’re applying the screen breakpoints.
- The units of the CSS property.
- The breakpoint values (of the screen as well as the CSS property).
- The media query type, i.e.: max-width, min-width, max-height, min-height.
And here it is…
breakpoints function above the final line may be a bit confusing. The Styled Components import
css is a Tagged Template Literal (ref). This means that
css([``]) are equivalent. This second implementation can be useful since it lets us set a template literal to a variable and then pass the variable into
We can now use this function to get rid of our clunky
@media queries and reformat our styled components as shown below.
This is a massive improvement — far more legible and easy to maintain!
For good measure I’ve put this example in Code Sandbox. Hopefully you’ll find it useful too.