Change color palette depending on variable in SCSS

Viewed 466

I have multiple components in my react app using a top navbar, sidebar, cards, etc. All share the same color palette (assets/css/variables.scss):

$nav-color: #009788;
$side-color: #9be7db;
$side-color-selected: #84ebdb;

What I want to do is to change these three colors depending on a variable, for example, a boolean returned by the login. Is this posible to achieve in the variable.scss file?

Obviously, I want to keep the variables names cause all the components use these variables. I only want to change the variables values.

1 Answers

You cannot do it purely with Sass, because sass is pre-rendered to CSS, so any variables are resolved to a value by the time they are delivered to the browser. However, you can point the Sass variables to CSS Custom Properties (Variables) and then update the value of the CSS variables with JS at your whim. Below is an example with CSS only-- but you can point Sass vars at CSS vars.

document.querySelector('#toggleTheme')
  .addEventListener('click', () => {
    const themeVar = '--theme-color';
    const themeColor = document.body.style.getPropertyValue(themeVar);
    const newThemeColor = themeColor === 'red' ? 'blue' : 'red';
    
    document.body.style.setProperty(themeVar, newThemeColor);
  });
:root {
  --theme-color: red;
}

h1 {
  color: var(--theme-color);
}
<h1>Hello World</h1>

<button id="toggleTheme">Toggle Theme Color</button>

Related