#Conditional SCSS style based on typescript variable

5 messages · Page 1 of 1 (latest)

south plover
#

I want to be able to conditionally add some styling depending on a particular typescript variable in a layout or component.

For example, say I have a boolean const redTitles = true in a Base.astro layout.

I want to be able to write some SCSS (not just plain CSS) that only activates when this variable is true. So far I've tried these two approaches:

---
const redTitles = true
---

{redTitles && <style lang="scss">
  main {
    h1, h2, h3, h4, h5, h6 {
      color: red;
    }
  }
</style>}

This just puts the raw style tag with lang="scss" and without transpiling the code to css into the final html page, and of course since it's scss and not css it doesn't work.


I've also tried this:

---
const redTitles = true
---

<style lang="scss" define:vars={{hasRedTitles: redTitles}}>
  @if $hasRedTitles {main {
    h1, h2, h3, h4, h5, h6 {
      color: red;
    }
  }}
</style>

This just errors out, the scss compiler says that there is no variable called hasRedTitles.

digital sedge
#

define:vars is definitely not what you looking for, since it implies that the style tag will not be bundled at all, just inlined (which does not work for SCSS. this is a common problem in any framework or lib really, and that's why many people go to css-in-js approach. i do really think that you must manipulate class names rather than dynamically inject css into the page; it isn't really a good practice doing so, since the compiler won't be able to tell whether it should bundle the SCSS or when.

south plover
#

Manipulating class names is not an option, this style also needs to be applied to mdx files, so it cannot depend on classes. I could use container classes, but that's less than ideal, plus it means I have to dirty up my template code with tons of classes for all the variables that need to manipulate the style

digital sedge
#

then you gotta discard the necessity of using SCSS for that specific snippet

digital sedge
#

just as a matter of curiosity