Responsive Design with Styled Components

How can we use styled-components when implementing a responsive design?

css, nextjs, react, styled-components

First lets make using media queries nicer.

Lets create a file that exports a media object with all the media queries we will need.

1
Always good to define breakpoints as constants so we can reference them later if needed. CSS Variables are also ok but I define them in terms of TS constants to keep my options open.
TSX
// media.ts
export const1desktopWidth= 670
const mq = (strings: TemplateStringsArray, width: number) =>
`@media only screen and (${
strings.slice(0, strings.length - 1).join("") +
width +
strings[strings.length - 1]
})` as const
export const media = {
desktop: mq`min-width: ${desktopWidth}px`,
mobile: mq`max-width: ${desktopWidth - 1}px`,
}
1
Always good to define breakpoints as constants so we can reference them later if needed. CSS Variables are also ok but I define them in terms of TS constants to keep my options open.

Import the media object into the file of your component and use like so:

TSX
// myComponent.tsx
import { media } from "./media"
const MyComponent = styled.span`
${media.desktop}{
background-color: green;
}
${media.mobile}{
background-color: pink;
}
`

Much nicer than typing out a media query every 5 seconds right?

What about hiding/showing components depending on the device size?

Lets add some more to the media.ts file.

1
Show the content by default.
2
Hide the content if the media query is activated.
TSX
// media.ts
...
export const hideOn = (size: keyof typeof media) =>
`1display: contents;
${media[size]} {
2display: none;
}
`
const hideOnDesktop = hideOn("desktop")
export const HideOnDesktop = styled.div`
${hideOnDesktop}
`
1
Show the content by default.
2
Hide the content if the media query is activated.

Now we can wrap our components ensuring they are only rendered on the appropriate device:

TSX
import { media, HideOnDesktop } from "./media"
...
<>
<HideOnDesktop>
<MobileOnlyContent />
</HideOnDesktop>
</>
...

For more tips on implementing responsive design with styled-components and NextJS, see this article.

Subscribe

No Webmentions for this post yet!