最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a way to dynamically update scss variables using JS in react? - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Nov 7, 2020 at 16:31 ShujathShujath 1,1711 gold badge11 silver badges24 bronze badges 1
  • You can use the classnames package to help you manage scss classes in you javascript. – Striped Commented Nov 7, 2020 at 16:34
Add a comment  | 

2 Answers 2

Reset to default 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');

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.

发布评论

评论列表(0)

  1. 暂无评论