Utilizing Dynamic Styling in Salesforce’s LWC

In LWC component development, dynamic styling becomes crucial in various scenarios. This article delves into the process of dynamically altering and defining classes through JavaScript.

Custom styling is typically achieved by adding a CSS file with the component name within the LWC structure. For instance, if the component is named “paginator,” a corresponding “paginator.css” file can be created alongside “paginator.html” and “paginator.js”.

Numerous use cases exist, but this article focuses on exploring two specific scenarios.

Scenario 1:

Within your application, enabling administrators to configure theme styling such as background color, button hues, and more, directly influences the UI based on their choices.

To accomplish this, defining a property within your JavaScript file allows for dynamic alteration based on the specified settings. This property, serving as a class, can be employed like so:

SampleApp.html file

<template>
    <div class="{customClass}">Salesforce Learning</div>
</template>

SampleApp.css file

.redColor {
    color: red;
}

.greenColor {
    Color: green;
}

sampleApp.js file

import { LightningElement, api, track } from 'lwc';

/**
 * Show an item
 */
export default class SampleApp extends LightningElement {
    @track customclass = 'redColor'; // you can set this parameter basis of admin selection

    changeTheme() {
        this.customclass = 'greenColor';
    }
}

Scenario 2:

Within your application, the aim is to include or exclude specific styling from an element.

For instance, suppose there’s a div element for which you intend to add or remove a class.

sampleApp.html file

<template>
    <div class="redColor" data-id="myDiv">Salesforce Learning</div>
    <lightning-button label="Green" onclick={changeGreen}></lightning-button>
    <lightning-button label="Default" onclick={noColor}></lightning-button>
</template>

sampleApp.css file

.redColor {
    color: red;
}

.greenBorder {
    border: 1px solid green;
}

sampleApp.js file

import { LightningElement, api, track } from 'lwc';

/**
 * Show an item
 */
export default class SampleApp extends LightningElement {
    noColor(){
        this.template.querySelector('[data-id="myDiv"]').classList.remove('greenBorder');
    }
    changeGreen(){
        this.template.querySelector('[data-id="myDiv"]').classList.add('greenBorder');
    }
}

In this demonstration, I’ve employed fundamental JavaScript techniques to modify the styling within my div element.

I trust this example serves as a comprehensive guide for addressing your dynamic styling requirements. Should you require additional support for your project, feel free to reach out to our Salesforce consulting team. Our seasoned developers specialize in offering Salesforce development services across various Salesforce products.