In this article, we will see how to use media queries in styled components.
Project setup
Create a react application using the following command:
npx create-react-app styled-components-media-queries
Install the styled-components package:
npm i styled-components
Add the following code in App.js
import React from "react"
import styled from "styled-components"
import { devices } from "./constants"
const Items = styled.p`
margin: 10px;
display: flex;
gap: 10px;
flex-direction: column;
`
const Item = styled.p`
padding: 10px;
flex: 1;
border: 1px solid;
`
const App = () => {
return (
<div>
<Items>
<Item>1</Item>
<Item>2</Item>
</Items>
</div>
)
}
export 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.
const breakpoints = {
xs: "320px",
sm: "640px",
md: "768px",
lg: "1024px",
xl: "1280px",
"2xl": "1536px",
}
export const devices = {
xs: `(min-width: ${breakpoints.xs})`,
sm: `(min-width: ${breakpoints.sm})`,
md: `(min-width: ${breakpoints.md})`,
lg: `(min-width: ${breakpoints.lg})`,
xl: `(min-width: ${breakpoints.xl})`,
"2xl": `(min-width: ${breakpoints["2xl"]})`,
}
Applying media query
We can apply media query in styled components in the same way we apply media queries in CSS:
import React from "react"
import styled from "styled-components"
import { devices } from "./constants"
const Items = styled.p`
margin: 10px;
display: flex;
gap: 10px;
flex-direction: column;
@media only screen and ${devices.md} {
flex-direction: row;
}
`
const Item = styled.p`
padding: 10px;
flex: 1;
border: 1px solid;
`
const App = () => {
return (
<div>
<Items>
<Item>1</Item>
<Item>2</Item>
</Items>
</div>
)
}
export default App
Now i=on larger screens, the items will be aligned next to each other.
Top comments (0)