Reputation: 909
So Sass has some really nice functions to create complex logic inside your css. It would be great if you could actually pass on data from a front-end framework like React or Svelte, and pass it on to your SCSS and have it update. A conceptual example:
page.tsx
onClick={setColor(element.Color = 'blue')}
style.scss
element {
color: $element.Color:
}
I'm pretty sure it's not possible at the current stage, since SCSS is just compiled into CSS. But does anyone know of any new innovations or framework exploring this? Or some pattern that comes close to this experience (excluding CSS-in-JS frameworks)?
Upvotes: 0
Views: 107
Reputation: 6146
CSS variables can be changed during runtime, unlike their SCSS counterparts. But you can use both in SCSS. The former will only hold any meaningful value during runtime and can't be used as input to any SASS functions.
If you need any logic to be performed on those values that goes beyond what calc()
can do you will have to use a javascript function during runtime.
Here is an example that shows how a user-provided value during runtime can be propagated into the CSS to influence the style rules:
const input = document.getElementById('input');
const container = document.querySelector('.container');
const onChange = (e) => {
container.style.setProperty('--items-per-line', e.target.value);
};
input.addEventListener('input', onChange);
.container {
--items-per-line: 4;
display: flex;
flex-wrap: wrap;
gap: 10px;
padding-right: calc(100% - (var(--items-per-line) * (20px + 10px)));
}
.item {
background: #ddd;
height: 20px;
width: 20px;
}
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<label>
desired items per line
<input id="input" />
</label>
A combination of SCSS and CSS vars can be used thus:
$items-per-line: 4;
$item-size: 20px;
$gap-size: 10px;
.container {
--items-per-line: #{$items-per-line};
display: flex;
flex-wrap: wrap;
gap: $gap-size;
padding-right: calc(100% - (var(--items-per-line) * #{$item-size + $gap-size}));
}
.item {
background: #ddd;
height: $item-size;
width: $item-size;
}
Upvotes: 1
Reputation: 513
I would make a scss function or class like "text-blue" and use that in the JS. JS is not meant to control styles, that's what css is for.
Upvotes: 0