Lightning Web Component usage if: true and if: false to make conditional rending on UI at runtime. There was an issue with this conditional directive related to performance and chaining of conditions. Salesforce introduced new LWC conditional directives to better performance and code visibility. This post will explain the new lwc: if, lwc: elseif, and lwc: else conditional directives in LWC.
Before we understand new conditional directives, let us first see what was the issue with the existing way of writing conditional directives.
Let us take an example, we have a requirement to show different sections based on the product vendor selected by the customer on the e-Commerce platform.
<template>
<template if:true={isVendorMac}>
<h1>Mac Products</h1>
<c-mac-products ></c-mac-products >
</template>
<template if:false={isVendorLP}>
<template if:true={isVendorApple}>
<h1>Apple Products</h1>
<c-apple-products ></c-apple-products >
</template>
<template if:false={isVendorDell}>
.....
</template>
</template>
</template>
</template>
In the above code, I feel the below issues
- Readability – The code does not look good to understand for a developer. It has not easy to understand code.
- Performance- We have to execute more conditions to evaluate else if conditions so it will be slower than normal rendering. For else conditions also if:false will be evaluated which is extra code execution and will slow down its rendering.
Both issues are resolved using new lwc: if, lwc: elseif, and lwc: else directives. Let us write the same code with new directives.
<template>
<template lwc:if={isVendorMac}>
<h1>Mac Products</h1>
<c-mac-products ></c-mac-products >
</template>
<template lwc:elseif={isVendorApple}>
<h1>Apple Products</h1>
<c-apple-products ></c-apple-products >
</template>
<template lwc:elseif={isVendorDell}>
<h1>Dell Products</h1>
....
</template>
<template lwc:else>
<h1>All Other Products</h1>
....
</template>
</template>
It is a lot easier to understand new code and we will have less condition evaluation than the older approach.
Summary:
Use new lwc: if, lwc: elseif, and lwc: else directives for better visibility and performance of the LWC component. It will create well-organized code.
References for Conditional Directives in LWC
Render DOM Elements Conditionally
Similar Posts
Generic Notification Component in LWC
Reusable Custom Calendar LWC using FullCalendar Js Library
Custom Toast with custom duration In LWC
Dynamic Interaction Between Two LWCs
LWC Enhancement in Salesforce Winter ’23
Need Help?
Need some kind of help in implementing this feature, connect on linked-in profile.
2 comments
Hi Dhanik,
Can we use FullCalendar Scheduler in LWC?If so which version FullCalendar Scheduler is compatible.
Thankyou.
Hello Hari,
Please check our post Reusable Custom Calendar LWC using FullCalendar Js Library for this.
Thank You,
Dhanik