Is there a way to dynamically update scss variables using JS in react?
Asked Answered
D

2

10

Problem

I have two scss variables places in colors.scss file, I want to update the variable colors only from javascript based on a logic,

if(day){
  // update $backgroundColor to white
}else{
  // update $backgroundColor to black
}

More info:

I have tried :export{} which is not working and also document.documentElement.style.setProperty using global css variables. I am using reactjs for frontend development.

Delainedelainey answered 7/11, 2020 at 16:31 Comment(1)
You can use the classnames package to help you manage scss classes in you javascript.Nostalgia
S
16

You can assign css variable to $backgroundColor as

:root {
  --background-color: white;
}
$backgroundColor: var(--background-color);

and update variable in js as

 const day = true;
 const root = document.documentElement;
 root.style.setProperty('--background-color', day ? 'white' : 'black');
Shawnee answered 7/11, 2020 at 16:39 Comment(0)
P
3

You can't update scss variables since they are not exist in runtime (when JS is runs).

You can make 2 classes, one with each style, and apply one of the classes at runtime.

Prearrange answered 7/11, 2020 at 16:37 Comment(1)
You are right in a way, we cannot update scss variables directly, thus having a css variable placeholder helps in dynamic updation.Delainedelainey

© 2022 - 2024 — McMap. All rights reserved.