Of late, the ‘CSS in JS’ approach to organizing stylesheets in a project has become ever more popular in the React ecosystem. I think there are two main reasons for this:
- In a world where everything is a component, coupling styles with view code makes each component more manageable and sharable between projects.
That being said, most people seem to favor one of two approaches to implementing CSS in JS: styled-components, and emotion. Both are similar in many respects, but most of my experience has been with the larger of the two projects, styled components.
In this post, I’ll touch on what I think is one of the neatest parts of how styled components can be used: media templates! Here's what the styled components docs have to say about it:
Let me show you how I’m using this approach in my site:
I tuck the above code away in the
utils directory, and then whenever I need to use a media query in any component throughout the project I can import and use it like so:
And that's it! There are many more exciting aspects of how to extend styled components, but of all of them, this solution to media queries is by far the most elegant and unique in my view. Hope you enjoy using this as much as I do, and happy querying!