Skip to content
react

How to use media queries in styled components

Apr 5, 2023Abhishek EH2 Min Read
How to use media queries in styled components

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"
4
5const 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}
26
27export 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}
9
10export 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"
4
5const 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}
29
30export 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!

Leave a Comment

© 2023 CodingDeft.Com