Dynamic CSS classes in LWC

Nested ternaries in a class getter stop being readable the moment a second condition appears. A small classSet helper turns the same logic into a flat map of class name to condition.

You've probably encountered code with dynamic CSS classes in LWC done in this way:

Don't do this
get wrapperClass() {
    return this.shouldHaveMarginTop ? 'slds-var-m-top_medium' : 'slds-m-top_none';
}

Which is not the best solution - once there's gonna be more classes, more conditions - it will become unreadable.

Use a classSet helper instead

Create a utils or helper component (if you don't have one) and create a classSet function. A basic implementation would look like this:

javascript
function classSet(config) {
    return Object.keys(config)
        .filter(key => config[key])
        .join(' ');
}

export { classSet };

Then import it into your component and start using it:

Do this
get wrapperClass() {
    return classSet({
        'slds-var-m-top_medium': this.shouldHaveMarginTop,
        'slds-m-top_none': !this.shouldHaveMarginTop
    });
}
markup
<template>
    <div class={wrapperClass}></div>
</template>

You can use multiple classes and conditions in that way!

Transcribed by hand from the original slide. Plain-text version of the whole catalog