Dynamic CSS in Lightning Web Component

Are you looking for applying dynamic CSS in Lightning web Component? Lightning Web Component doesn’t allow computed expressions in html markup but there are ways to do so. The implementation of CSS for Lightning Web Components adheres to the W3C standard. You can create a style sheet in the CSS file, and it’s automatically applied to the corresponding HTML file.

Dynamic CSS in LWC – Using Getter

In Lightning Web Component, To compute a value for a property, use a JavaScript getter. Getters are much more powerful than expressions because they’re JavaScript functions. Getters also enable unit testing, which reduces bugs and increases fun.

Let’s see an example. I have created a Lightning web component with name app in Trailhead playground. The html file of the component is app.html. It has a div and a checkbox. Our aim is to change the CSS class of div whenever checkbox is checked.

<template>
    <!--className is defined as getter in js file-->
    <div class={className}>
        Dynamic Style
    </div>
    <lightning-input type="checkbox" label="Change Style"
    name="input1" value={changeStyle} onchange={handleChange}></lightning-input>
</template>

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

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {
    @track changeStyle = false;
    get className(){
      //if changeStle is true, getter will return class1 else class2
        return this.changeStyle ? 'class1': 'class2';
    }
    handleChange(event){
        this.changeStyle = event.target.checked;
    }
}

The CSS file of the component is pretty simple. There are two style class defined in it. The file name is app.css.

.class1 {
    height:29px;
    background: red;
}
.class2 {
    height:29px;
    background: blue;
}

Dynamic CSS in LWC – Using Getter – Demo

Are you looking for applying dynamic CSS or conditional CSS in your Lightning web Component?  Lightning Web Component doesn’t allow computed expressions in html markup
When checkbox is unchecked
In Lightning Web Component, To compute a value for a property, use a JavaScript getter. Getters are much more powerful than expressions because they’re JavaScript functions. Getters also enable unit testing, which reduces bugs and increases fun.
When checkbox is checked

Click this link to play with the above code in Trailhead Playground to understand dynamic CSS in Lightning web component:- https://developer.salesforce.com/docs/component-library/tools/playground/gv4VZbSv/19/edit

4 comments

Leave a Reply