This week I’d like to talk about how to build the ability to change branding into your React website using SCSS/CSS variables. In short, this is going to be the guide that I wish I had been able to read a few days ago.
Normally, the theme of your website is fairly static and doesn’t need to be changed, but if you have an application that you share with partner companies, and they want their own branding on it for their customers, then you can use a solution like this to apply that branding dynamically (like pulling the styles from a database or API call). You can use this technique whether you are using CSS alone or combining it with SCSS.
Before we get into the method of making the styles dynamic in React, let’s start with a quick primer on using variables in SCSS/CSS. I’ll start with SCSS because it rolls up into CSS, and in the CSS is where we really set the initial values of our variables. SCSS allows you to define variables that remove the hardcoding of property values so that you can easily use the same values across the different rules:
In this sample, I’ve defined three variables that hold three different colors I’d like to use on my site. I can easily change the values in my scss files to change the theme before I build my css files. To take advantage of the dynamic changing in React, we instead need to use CSS variables. This is done by changing the values in our SCSS files to the names of the CSS variables:
The rest stays the same. Now in a CSS file, I will define the variables that will be used at runtime:
Then you just pass this dictionary to the ThemeSwitcher component in your render method:
Here I have the theme defined directly in React, but you can imagine I add some code that resolves what the theme should be based on the requested URL. By putting the definition of the theme in the main App state, you can easily trigger a React refresh whenever you change the theme, such as changing the theme with a button on the page.
In this article, I talked about utilizing SCSS/CSS variables and the react-css-vars plugin to easily provide dynamic theming to your application. This can be especially useful if you have branding that is URL or database driven. I’ve mostly talked about colors, but you can use this for any CSS properties you use in your application.