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 | www.jordaneckowitz.com

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

Recommended from Medium

Measuring code execution time in browsers

Angular Dynamic Templates: How to Build an App With 3 Layout Styles

handwritten wireframe diagrams

The Internationalization API - JS

React Context API. Part 1 — Dark Theme

https://t.co/daxRJE47gK

ComponentStore — Introduction

Serve Angular Application in Python Flask Server

A beginner’s guide to Metro Bundler

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 | www.jordaneckowitz.com

More from Medium

React — css styled component

KFC (Kentucky Fried Chicken) Clone

Styled Components

How to trigger an event on scroll with pure REACT (without any package).