Saturday 5 March 2022

                                DYNAMIC CSS IN LIGHTNING WEB COMPONENT

This post explains how to create CSS in lightning web components and also how to use the dynamic CSS in web components using the getter property

Let’s see an example. I have created a Lightning web component named dynamic style. It has a div and a checkbox. Our aim is to change the CSS class of div whenever the checkbox is checked.

dynamicStyle.html

<template>
    <lightning-card title="Dynamic CSS using Getter">
        <div class={dynamicColorChange}>
            Dynamic Style
        </div>
        <lightning-input type="checkbox" label="ChangeStyle" value={changeColor} onchange={handleChange}>
        </lightning-input>
    </lightning-card>
</template>

Javascript

import { LightningElement } from 'lwc';

export default class DynamicStyle extends LightningElement {
    changeColor;
    handleChange(event){
        this.changeColor=event.target.checked;  
    }

    //If change color is true: using getter will return class 1 else class 2
    get dynamicColorChange(){
        return this.changeColor?'class1':'class2';
    }
}

     CSS: The same name as an LWC component and add .css in the file name for this example: dynamicStyle.css

.class1{
   height: 30px;
   background-color: aqua;
}

.class2{
    height:30px;
     background-color: chartreuse;
}


     The onchange handler is defined in the dynamicStyle.js file of the component. It is updating the value of the checkbox to a property defined. Along with it, the js file also has a getter to compute dynamically the CSS class of the div block defined in HTML.

        How to find who created the lightning web component 


 We can find aura and LWC in Setup > Quick find > Lightning Components. The Type column gives information on Aura/LWC. It provides CreatedBy, CreatedDate, and the LastModifiedDate of LWC and Aura.