I'm learning some ReactJS and Sass and was wondering if it's possible to import a Reactjs variable into Sass or assign a ReactJS element class name to a Sass variable.
I'm doing a silly quotes machine and I need different elements to change to the same color at the same time when I click a button. I alredy implemented a working solution, but because I'm trying to make a modularized code, I had to use react context and state. I learnt a lot, but I thought about two solutions I guess would be better if I could implement them, that would make the code so much cleaner with no need of context nor state.
I searched hours, but couldn't find a way to import a variable (that would change when I click the button) from the Reactjs file into the Sass file to use it there. Something like this:
Reactjs File:
let num = 0;
function randomNumber() {
num = Math.floor(Math.random() * (n + 1));
}
render (
<button onClick={randomNumber()} className={RandomColor}>Button</button>
)
Sass file:
//somehow import num
$color: blue, yellow, green, red...;
$i = num
.RandomColor {
background-color: nth($color, $i);
}
Found posts saying that I could export a Sass variable into Javascript file, but when I did it in my Reactjs file the variable is undefined.
After searching to that possibility I thought other way to comunicate was to change the class (or other property) of the button when I click it and assign that to a variable that would define the property I need to dynamically change. Something like this:
ReactJs file:
let num = 0;
function randomNumber() {
num = Math.floor(Math.random() * (n + 1));
}
render (
<button id='buttonID' onClick={randomNumber()} className={num}>Button</button>
)
Sass file:
$color: blue, yellow, green, red...;
//something like this
$i = .class of #buttonID
.RandomColor {
background-color: nth($color, $i);
}
Thanks in advance!