How to add breakpoints with Styled Components

Learn how to add breakpoints with styled components and adding the media queries correctly to styled components.

#Styled-Components#Responsive#CSS
Dom Vournias
Dom Vournias
Updated on: 29 Jun, 2022

How to use media queries with Styled Components

Styled Components breakpoints

If you want to apply responsiveness to your app, you will have to use media queries. If you're using Styled Components and you don't know how to add the breakpoints correctly, I will show you how to do it.


☚ī¸ From this



🤩 To that



Create the media queries

Create a file in this case we will name it Breakpoints.styled.js and create an object with the breakpoint names you want to use and assign for each of the names a value that represents the screen size you want to use.


Then we create an object called device and we assign again the values for each breakpoint name, but this time with the media querie parameter max-width or min-width dependand on how you will style your application.

From mobile to desktop use max-width


// Breakpoints.styled.js

// Thsese are the sizes
export const size = {
  mobileS: "320px",
  mobileM: "375px",
  mobileL: "425px",
  tablet: "768px",
  laptop: "1024px",
  laptopL: "1440px",
  desktop: "2560px",
};

// These are the queries
export const device = {
  mobileS: `(max-width: ${size.mobileS})`,
  mobileM: `(max-width: ${size.mobileM})`,
  mobileL: `(max-width: ${size.mobileL})`,
  tablet: `(max-width: ${size.tablet})`,
  laptop: `(max-width: ${size.laptop})`,
  laptopL: `(max-width: ${size.laptopL})`,
  desktop: `(max-width: ${size.desktop})`,
  desktopL: `(max-width: ${size.desktop})`,
};

Edit the styled element for the preferred breakpoint

Now that we have all the breakpoints and device sizes we can import it into our styled element.



  • Classic CSS Media Queries
@media (max-width: 1024px) {
  flex-wrap: wrap;
  align-items: flex-start;
}

Make sure to import the device from where you set the media queries.

  • Styled Components Media Queries
  import { device } from "./Breakpoints.styled";

  @media ${device.laptop} {
    flex-wrap: wrap;
    align-items: flex-start;
  }

As you can see we add device. and then the preferred screen size, for example laptop.


There you have it, that simple we can have globally in our project whatever screen sizes we want our app to be responsive to.


Make sure to check the PROJECT I used in this article in codesandbox.




😁 Make sure to like and share if you found this guide helpful.


ARTICLE REACTIONS

SHARE THIS POST

Dom Vournias Portfolio
Get in touch

If you want to work together on a project or to just have a chat, please don't hesitate to contact me.

about
Dom Vournias signature