A co-worker approached me with a curious question: "I've got a sass statement that I want to apply a variant to the parent, but still use it to house a class that I want to change based on that variant." Here's the code he showed me.

  #Namespace {
  .Component {
    &--featured &-title {
      //some styles.
    }
  }
}

// desired output
#Namespace .Component--featured .Component-title {}

// actual output
#Namespace .Component--featured #Namespace .Component-title {}

Typically, the easy thing to do is just repeat yourself a little.

  #Namespace {
  .Component {
    &--variant .Component-title {
    }
  }
}

That's a fine way to do it, but he would rather have the freedom to re-reference that .Component name when he needs it. That's when variables come into play.

  #Namespace {
  $component: ".Component";

  #{$component} {
    &--variant #{$component}-title {
    }
  }
}

//result
#Namespace .Component--variant .Component-title {}

This will produce the same result and he has the freedom to re-reference his component name throughout. The best part is that the variable is scoped inside of #Namespace. If you try to use the variable outside of that, Sass will complain and throw an error: Undefined variable: "$component".

Of course, this example is contrived - you're still re-writing component everywhere. This can become more useful when you have longer component names or need to reference other names deeper in your namespace.


84 0 0