Conditional display in LWC through lwc:if, lwc:elseif, and lwc:else

Previously, to conditionally render HTML, we employed the if:true|false directive within a nested <template> tag encompassing the conditional content. However, the Spring ’23 release introduced new conditional directives – lwc:if, lwc:elseif, and lwc:else – enabling Conditional Rendering in LWC. This blog post delves into these directives and their superiority over the legacy if:true and if:else directives, demonstrating how lwc:if, lwc:elseif, and lwc:else supersede their predecessors.

What is Conditional Rendering in LWC?

Conditional rendering within the Lightning Web Component (LWC) allows components or elements to be displayed depending on particular conditions. For instance, varying greeting messages can be shown based on the time of day.

Conditional Rendering in LWC using lwc:if, lwc:elseif and lwc:else.

Let’s see how to use lwc:if, lwc:elseif and lwc:else in lightning web components. With the new lwc:iflwc:elseif, and lwc:else conditional directives, the property getters are accessed only one time per instance of the directive. Here is an example of how we can use it.

<template>
    <template lwc:if={expression1}>
        Statement 1: Hi
    </template>
    <template lwc:elseif={expression2}>
        Statement 2 : Hello
    </template>
    <template lwc:else>
        Statement 3 : How are you?
    </template>
</template>

The legacy if:true and if:else directives are no longer recommended as Salesforce intends to deprecate and remove these directives in the future. Salesforce recommend that you replace their usage with the new conditional directives to future-proof your code

if:true and if:false

This is conditional rendering using if:true and if:false:

<template>
 <template if:true={condition1}> Hello Apex Hours </template>
 <template if:false={condition1}>
 <template if:true={condition2}> If </template>
 <template if:false={condition2}> Else </template> </template> </template>

Consideration for lwc:if, lwc:elseif and lwc:else

    • You can’t precede lwc:elseif or lwc:else with text or another element.
    • you can’t have a <div> tag that comes after lwc:if and before lwc:else
    • Complex expressions like !condition or object?.property?.condition aren’t supported. To evaluate complex expressions, use a getter in your JavaScript class.