Site icon WedgeCommerce

Conditional Rendering in LWC

To render HTML conditionally in LWC we have if:true|false directive like we used <aura:if> in aura components.

For conditional rendering we just need to add the if:true|false directive to a nested <template> tag that encloses the conditional content.

The if:true|false={property} directive binds data to the template and removes and inserts DOM elements based on whether the data returns a true or a false value.

Below is an example for conditional rendering in LWC in which we are rendering an image based on a toggle button.

 

ConditionalRendering.html

<template>
    <lightning-card title="Conditional Rendering in LWC" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <div class="slds-form-element">
                <label class="slds-checkbox_toggle slds-grid">
                  <span class="slds-form-element__label slds-m-bottom_none">Show Image</span>
                  <input type="checkbox" name="checkbox-toggle-16" value="checkbox-toggle-16" aria-describedby="checkbox-toggle-16" onchange={handleChange}/>
                  <span id="checkbox-toggle-16" class="slds-checkbox_faux_container" aria-live="assertive">
                    <span class="slds-checkbox_faux"></span>
                    <span class="slds-checkbox_on">Enabled</span>
                    <span class="slds-checkbox_off">Disabled</span>
                  </span>
                </label>
              </div>
            <template if:true={isVisible}>
                <div class="slds-m-vertical_medium">
                    <div><img src={pictureUrl}/></div>
                </div>
            </template>
        </div>
    </lightning-card>
</template>

 

ConditionalRendering.js

 

import { LightningElement } from 'lwc';

export default class ConditionalRendering extends LightningElement {
    isVisible = false;
    pictureUrl = 'https://d259t2jj6zp7qm.cloudfront.net/images/20200821155946/Winter_21_logo_RGB_V2-e1598285037330.png';
    handleChange(event) {
        this.isVisible = event.target.checked;
    }
}

Exit mobile version