We encounter a no of scenarios in which we require dynamic styling in LWC component development. In this blog, we will learn about changing and setting class 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 a various use case, here we will discuss two.
Usecase 1:
In your app, you want to provide a setting for 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 value of the property. That property can be used as a class. Ex :
SampleApp.html
SampleApp.css
sampleApp.js

Also Read: How To Use Properties In Lightning Web Component?
Usecase 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
sampleApp.css
sampleApp.js
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.