Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

How to use if .. else if in LWC?

Earlier we had to execute if:true a lot of times to conditional render the markup in LWC. With Spring 23 we can use if .. else if in the LWC template files and it becomes a lot easier to render markup conditionally.

By Teja, ex-Salesforce engineer · Updated March 16, 2023 · 1 min read

In this blog post, I did walk you through how to render conditional markup in LWC.

With the latest Spring '23 release we will be able to use if .. else if tags in the LWC template files to achieve conditional markup rendering.

Here's a simple example demonstrating it.

<template>
    <template lwc:if={leapYear}>
        <p>YES! It's a leap year</p>
    </template>
    <template lwc:elseif={notLeapYear}>
        <p>NO! It's not a leap year</p>
    </template>
    <template lwc:else>
        <p>I don't know man!</p>
    </template>
</template>

conditionalRendering.html

import { LightningElement } from 'lwc';

export default ConditionalRendering extends LightningElement {

	get leapYear(){
    	const d = new Date();
		let year = d.getFullYear();
    	return handleLeapYearCalculation(year);
    } 
    
    get notLeapYear(){
    	const d = new Date();
		let year = d.getFullYear();
    	return handleLeapYearCalculation(year);
    } 
    
    handleLeapYearCalculation(year){
    	if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {
        	return true;
    	} else {
        	return false;
    	}
    
    }

}

conditionalRendering.js

Hope this is helpful!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts