In this tutorial we will create some useful shortcuts to make implementing responsive designs with Styled Components a piece of cake.
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.
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"
constMyComponent= 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
...
exportconsthideOn=(size:keyoftypeof media)=>
`1display: contents;
${media[size]} {
2display: none;
}
`
const hideOnDesktop =hideOn("desktop")
exportconstHideOnDesktop= 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.