Hello friends, today we are going to discuss how to Use Dynamic Styling In LWC Salesforce. Our goal here is to learn how to change the class dynamically from js.
Also, check this: Navigate from LWC component to another LWC Component
Key Highlights :
- We will add a CSS file to define design classes and ids.
- We can assign a CSS class by getter.
Code :
lWCDynamicCSS.HTML :
<template>
<div class="app slds-p-around_x-large">
<article class={divBackground}>
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2 class="slds-card__header-title">
<a href="#" class="slds-card__header-link slds-truncate" title="Accounts">
<span>Accounts</span>
</a>
</h2>
</div>
<div class="slds-no-flex">
<button class="slds-button slds-button_neutral" onclick={handleClick}>Change Background</button>
</div>
</header>
</div>
</article>
</div>
</template>
lWCDynamicCSS.JS :
import { LightningElement } from "lwc";
export default class LWCDynamicCSS extends LightningElement {
isColorfull = false;
/**
* Getter for the css property
*/
get divBackground() {
return this.isColorfull ? "slds-card backgroundColor" : "slds-card backgroundNoColor";
}
handleClick(){
this.isColorfull = !this.isColorfull;
}
}
lWCDynamicCSS.CSS :
.backgroundColor {
background-color: rgb(0, 112, 210);
color:white;
}
.backgroundNoColor{
background-color: rgb(247, 247, 247)
}
Output :
Reference :
What’s your Reaction?
+1
3
+1
+1
1
+1
+1
1
+1
1 comment
cool!