How to use global mixins and variables with CSS Modules in React with SASS
• 2 min read
Introduction
These days it’s fairly common to use different CSS frameworks or libraries to handle styling in a React app such as Tailwind or styled-components. Typically I tend to prefer more traditional CSS with separated files.
Outside of the arguments of why this may be preferred or not it’s still fairly useful to have a set of global mixins (SASS) and/or variables to keep it DRY.
Starting an app with Create-React-App or next a fairly common option is to use CSS Modules which guarantees that the styles per component will not have any conflicts, however, it does mean it’s slightly different to access these global variables.
This tutorial assumes you already have a react app ready to configure.
The package
Create-react-app docs recommend using node-sass for the styling, however, this is deprecated so I would suggest using sass (Dart Sass) as it is still actively receiving support. This can be quickly done with:
Bash/Shellyarn add sass
or
Bash/Shellnpm install sass
The stylesheet
Now with that out of the way let’s create a file for our mixins with the name _variables.scss:
Mixin stylesheet
In the actual style sheet, it can be imported in the following way (any file *.module.scss):
Imported mixins
Variables
For variables it would be something very similar, let’s have a file with the name _variables.scss:
Variable stylesheet
And importing it can be done in a similar fashion:
This can be quite useful to reuse a lot of variables and similar styles throughout the entire project while still maintaining the module structure.
For example, I did something along these lines to share variables to use in media queries throughout my project:
Example stylesheet
This is quite useful as I used a combination of CSS variables and SASS variables to reuse a lot of fixed sizes and paddings to keep everything standardized throughout the entire app.
If you see any typos or errors you can edit the article directly on GitHub
Hi, I'm Diego Ballesteros 👋.
Stay on top of the tech industry and grow as a developerwith a curated selection of articles and news alongside personal advice, observations, and insight. 🚀
No spam 🙅♂️. Unsubscribe whenever.
You may also like these articles:
- 2023-06-05T00:41:29.681Z
- 2022-10-25T11:29:26.663Z
- 2022-10-17T14:44:10.229Z
- 2022-10-10T14:02:10.349Z