We used to add the if:true|false directive to a nested <template> element that enclosed the conditional content to render HTML conditionally. Nevertheless, with Spring 23, we may use new lwc:if, lwc:elseif, and lwc:else to do Conditional Rendering in LWC.
In this blog article, we will discuss the lwc:if, lwc:elseif, and lwc:else conditional directives that were added in the Spring'23 release. We will also look at how the lwc:if, lwc:elseif, and lwc:else conditional directives supplant the old if:true and if:else directives.
What Is Conditional Rendering?
Conditional rendering is a method of displaying components or elements based on a given circumstance in the lightning web component (lwc).
This template has a Show Message checkbox. The handleChecboxChange function sets the value of the showMessage property when a user chooses or deselects the checkbox. If the showMessage attribute is set to true, the lwc:if directive shows the nested template Good Morning! Otherwise, it will show select the checkbox to see the message!.
<!-- conditionalRendering.html -->
<template> <lightning-card title="ConditionalRendering" icon-name="custom:custom14"> <div class="slds-m-around_medium"> <lightning-input type="checkbox" label="Show Message" onchange={handleChecboxChange}></lightning-input> <template lwc:if={showMessage}> <div class="slds-m-vertical_medium"> Good Morning! </div> </template> <template lwc:else> <div class="slds-m-vertical_medium"> <b> select the checkbox to see the message ! </b> </div> </template> </div> </lightning-card></template>
It is important to note that the JavaScript does not affect the DOM; instead, it merely changes the value of a property.
// conditionalRendering.js
import { LightningElement } from 'lwc';
export default class ConditionalRendering extends LightningElement { showMessage = false;
handleChecboxChange(event) { this.showMessage=event.target.checked; }}