How I Use Mixins in Sass
Sass has helped me add more functionality to my CSS code.
Once I decided to introduce dark mode to my website, I realized I had to have a light mode and a dark mode style for the same component in many instances throughout my code.
Instead of duplicating the same CSS for both the light and dark mode styles, I utilized Sass mixins to define styles that could be re-used throughout my stylesheet.
Mixins in Sass
I added an argument to the mixin that specified the theme (dark or light mode) and based on that the corresponding background and font colours were applied.
The mixin was defined with the general properties for both dark and light mode themes, and with the specific theme properties. Then each of the theme styles included that mixin as part of their CSS body.
The light mode
blog-content style didn’t pass any arguments to the mixin since by default the mixin took on the light mode. For
blog-content-dark the argument passed into the mixin had to be set to
dark=true , after which the condition in the if statement within the mixin was met.
Thus by choosing Sass over regular CSS, more flexibility and functionality could be introduced to my stylesheet.
Adding The Styles In React
To use the two styles above, I had to import them from a Sass module file and add them to the
className property of a react component as follows:
Based on some arbitrary theme state defined in the React application, the appropriate theme was applied to the blog content. If the theme was set to true the class
blogContentDark was applied, and vice-versa. The CSS classes were imported from a scss module file.
This is the way I have been employing mixins in my applications so far as I learn more about the amazing things Sass can do. Please let me know if there are better ways of using mixins or Sass in general for my use case above.