crosie
crosie

Reputation: 45

Update Sass (SCSS) variables programmatically from React

This is a valid sass code.

$dark-theme: true !default;
$primary-color: #f8bbd0 !default;
$accent-color: #6a1b9a !default;

@if $dark-theme {
  $primary-color: darken($primary-color, 60%);
  $accent-color: lighten($accent-color, 60%);
}

.button {
  background-color: $primary-color;
  border: 1px solid $accent-color;
  border-radius: 3px;
}

So, it is possible to change variables based upon conditions. But, how do we update these variables from the frontend? I want to change the value of $dark-theme to false on a press of a button in the frontend? Is it possible to do so? How?

Upvotes: 0

Views: 597

Answers (1)

David Yappeter
David Yappeter

Reputation: 1612

No it's not possible to change the sass, but you can do it like this

html {
  --lightBtn: #FE016C;
  --lightBg: #fff;
  --lightColor: #232323;
}

html[data-theme='dark'] {
   background: var(--lightBg);
  --lightBtn: #FFBD07;
  --lightBg: #232323;
  --lightColor: #fff;
}

And the button will toggle the attribute

        buttonElement.addEventListener('change', function() {
            if(this.checked) {
                trans()
                document.documentElement.setAttribute('data-theme', 'dark')
            } else {
                trans()
                document.documentElement.setAttribute('data-theme', 'light')
            }
        })

other Selector


h1 {
  font-family: 'Poppins', sans-serif;
  font-weight: 300;
  color: var(--lightColor); 
}

color will change according to data-theme

credit: https://codepen.io/KaioRocha/pen/MdvWmg

Upvotes: 3

Related Questions