Theming Components with SCSS Mixins
In a recent blog post about React style composition with SCSS I was asked about theming in relation to composable SCSS mixins. The good thing is, this approach works perfectly fine with theming, because SCSS supports variables and named parameters, as demonstrated in the code below:-
You could declare the base theme default file like so:-
// defaultVariables.scss
$defaultBackgroundColor: blue;
$defaultColor: red;
Then, you can declare parameterized mixins which import the theme defaults defaultVariables.scss
and which leverage named arguments. These named arguments can be overiden in different contexts to enable composition, but also fall back to the current theme by default if nothing is specified.
// spinnerComp.scss
@import "./defaultVariables.scss"
// now pass in the defaults from defaultVariables.scss in the mixin declaration like this:
@mixin spinnerComp($backgroundColor: $defaultBackgroundColor, $color: $defaultColor) {
&--spinner {
background-color: $backgroundColor;
color: $color;
}
}
Then, include the mixin in different contexts and skin accordingly.
// arbitrary contexts
.page {
@include spinnerComp();
}
.list-item {
// Note that you can now provide named parameters to the mixin instance, meaning that you can keep some, all or none of the original defaults as you see fit.
@include spinnerComp($color: green, $backgroundColor: yellow);
}
.card {
@include spinnerComp($color: orange);
}
As you can see, if you change the variables in defaultVariables.scss
then any conventional instances of spinnerComp will inherit those new variables, enabling nice heirarchal theming.