Jimmy
Jimmy

Reputation: 3850

Dynamic class names in SASS

I am new to SASS. I want to create an element with a dynamic class name that I can then easily control in my SASS. Something like one of the two psuedo examples below. How do I do this in SASS? Thanks!

EXAMPLE 1:

--- React JS ---
<div className={this.state.onClick ? "menu-on" : "menu-off"}></div>

--- SASS ---

.menu-{x} {
  x = "on": {
    background-color: blue;
  }
  x = "off": {
    background-color: red;
  }
}

EXAMPLE 2:

--- React JS ---

<div className={"menu " + (this.state.onClick ? "on" : "off")}></div>

--- SASS ---

.menu {
  .on {
    background-color: blue;
  }
  .off {
    background-color: red;
  }
}

Upvotes: 4

Views: 2037

Answers (1)

net.uk.sweet
net.uk.sweet

Reputation: 12431

You can't control SASS from React since it's essentially static once you've compiled it to CSS.

However, I think your second example will work if you change the SASS to the following:

.menu {
  &.on {
    background-color: blue;
  }
  &.off {
    background-color: red;
  }
}

Which will compile to the following CSS:

.menu.on {
    background-color: blue;
}
.menu.off {
    background-color: red;
}

Upvotes: 4

Related Questions