We encounter a number of scenarios requiring dynamic styling in LWC component development. In this blog, we will learn about changing and setting classes dynamically from js.
We all know that in order to write any custom style, we can add a css file in our LWC component named with the app name. Ex: If my component name is paginator then I can create a paginator.css file parallel to paginator.html and paginator.js.
There can be various use cases; here, we will discuss two.
Use case 1:
In your app, you want to provide a setting for the admin to decide theme styling like background color, button colors, etc. Basis of its selection, UI has that change
To achieve this, you can declare a property in your js file, and the basis of your setting can change the property’s value. That property can be used as a class. Ex :
SampleApp.html
<template>
<div class="{customClass}">Salesforce Learning</div>
</template>
SampleApp.css
.redColor {
color: red;
}
.greenColor {
Color: green;
}
sampleApp.js
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';
}
}
Use case 2:
In your app, you want to add or remove styling from any element
Let’s say I have a div, and I want to add or remove a class from my div element.
sampleApp.html
<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
.redColor {
color: red;
}
.greenBorder {
border: 1px solid green;
}
sampleApp.js
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 example, I have used basic JS to manipulate styling in my div element.
Hope this example helps you to solve all your dynamic styling-related needs. If you need further assistance regarding a project of yours, then get in touch with our salesforce consulting team. Our team consists of expert developers providing salesforce development services for various salesforce products.