Use Dynamic Styling In LWC Salesforce

by Rijwan Mohmmed
use-dynamic-styling-in-lwc-salesforce-techdicer

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

use-dynamic-styling-in-lwc-salesforce-output-techdicer
use-dynamic-styling-in-lwc-salesforce-output-techdicer

Key Highlights :

  1. We will add a CSS file to define design classes and ids.
  2. 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 :

use-dynamic-styling-in-lwc-salesforce-output-techdicer
use-dynamic-styling-in-lwc-salesforce-output-techdicer

Reference :

  1. CSS in LWC
What’s your Reaction?
+1
3
+1
0
+1
1
+1
0
+1
1
+1
0

You may also like

1 comment

bob June 5, 2023 - 2:42 pm

cool!

Reply

Leave a Comment