Responsive Styled Components | Breakpoints Function

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, StyledThis and StyledThat.

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 padding, font-size and 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…

In the 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`` and 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 css, hence css([breakpointProps]).

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.




Full-Stack Web Developer |

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Finding the Happy Medium for Abstraction

Finding the Happy Medium for Abstraction

Magical React component that provides exceptional moving particles’ background

Chain of Responsibility Design Pattern

Implementing the Queue Data Structure using an array in Javascript

React: Form for Contact Add

21 Useful Things You Could Do From Chrome Address Bar

Why React Native?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jordan Eckowitz

Jordan Eckowitz

Full-Stack Web Developer |

More from Medium

Use breackpoints as css classes in emotion react

Cheat Sheets that always save my time during web development 🚀

Scroll Section to Section Animation with JavaScript

Styled Components