Table of Contents
In this article, we will see how to use media queries in styled components.
Project setup
Create a react application using the following command:
1npx create-react-app styled-components-media-queries
Install the styled-components package:
1npm i styled-components
Add the following code in App.js
1import React from "react"2import styled from "styled-components"3import { devices } from "./constants"45const Items = styled.p`6 margin: 10px;7 display: flex;8 gap: 10px;9 flex-direction: column;10`11const Item = styled.p`12 padding: 10px;13 flex: 1;14 border: 1px solid;15`16const App = () => {17 return (18 <div>19 <Items>20 <Item>1</Item>21 <Item>2</Item>22 </Items>23 </div>24 )25}2627export default App
Here we have 2 blocks of items that are aligned vertically. If we need to align them horizontally next to each other on large screens, then we need to apply media queries.
Creating breakpoints
Before applying media queries, let's create breakpoints that can be reused.
constants.js
1const breakpoints = {2 xs: "320px",3 sm: "640px",4 md: "768px",5 lg: "1024px",6 xl: "1280px",7 "2xl": "1536px",8}910export const devices = {11 xs: `(min-width: ${breakpoints.xs})`,12 sm: `(min-width: ${breakpoints.sm})`,13 md: `(min-width: ${breakpoints.md})`,14 lg: `(min-width: ${breakpoints.lg})`,15 xl: `(min-width: ${breakpoints.xl})`,16 "2xl": `(min-width: ${breakpoints["2xl"]})`,17}
Applying media query
We can apply media query in styled components in the same way we apply media queries in CSS:
App.js
1import React from "react"2import styled from "styled-components"3import { devices } from "./constants"45const Items = styled.p`6 margin: 10px;7 display: flex;8 gap: 10px;9 flex-direction: column;10 @media only screen and ${devices.md} {11 flex-direction: row;12 }13`14const Item = styled.p`15 padding: 10px;16 flex: 1;17 border: 1px solid;18`19const App = () => {20 return (21 <div>22 <Items>23 <Item>1</Item>24 <Item>2</Item>25 </Items>26 </div>27 )28}2930export default App
Now i=on larger screens, the items will be aligned next to each other.
Do follow me on twitter where I post developer insights more often!