How to use CSS Media Queries with Styled Components in React.js

Just like regular CSS, you write your Media Queries in your CSS file. In Styled Components, you can include them as well.
import styled from 'styled-components'
export const Columns = styled.div`
padding-top: 2rem;
display: grid;
gap: 2rem;
@media (min-width: 769px) {
grid-template-columns: 2fr 3fr;
}
`
But if you want to make it smart, you set all the sizes in an Object and create a function to call them from your styled-components in React.
Create a file breakpoints.tsx
.
const size = {
xs: '320px',
sm: '768px',
lg: '1024px',
xl: '1200px',
}
const mediaQueries = (key: keyof typeof size) => {
return (style: TemplateStringsArray | String) => `@media (min-width: ${size[key]}) { ${style} }`
}
export { size, mediaQueries }
Import the file in the component where you defined your styled-components, and you can easily use your media queries without remembering your exact sizes.
// File where you defined your styled components
import { mediaQueries } from 'styles/components/breakpoints'
export const Columns = styled.div`
padding-top: 2rem;
display: grid;
gap: 2rem;
${() => mediaQueries('sm')(`grid-template-columns: 2fr 3fr;`)}
`
I believe in making it yourself as simple as possible, so hopefully, this solution will help you further.
Thanks!
After reading this post, I hope you learned something new or are inspired to create something new! 🤗
If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM’s are always open 😁
Suggestions
Improve React Components With Optional Chaining & Nullish Coalescing
If you’re working on a big React (Next.js) application, sometimes you might need to dive deep into a data structure. Let's use Optional Chaining & Nullish Coalescing to improve React components.
Polished.js: A Utility CSS-in-JS library for Styled-Components in React.js
Sass functions like lighten(), darken(), complement(), invert() are pretty useful. I was wondering if there was something for styled-components. Well, I found the great library Polished.js.
How To Add Props To Styled Components in React.js with TypeScript
I’m pleased with Styled-components. Adding proper TypeScript typings was a big question for me, until now! So I want to share them with you. 😉