Conditional rendering is a powerful feature in LWC that allows you to dynamically show or hide content based on specific conditions.
Fresh Instruction in Lightning Web Components (LWC):
Starting from Spring’23, Salesforce introduced new directives for conditional rendering: lwc:if, lwc:elseif, and lwc:else. These directives are more recommended than the legacy if:true|false .
Initial One: Basic Conditional Display
This snippet will be helpful for how to display different greetings based on the user’s name:
<template>
<template lwc:if={userName === 'Jack'}>
Hi Jack, welcome back!
</template>
<template lwc:elseif={userName === 'Rock'}>
Hello Rock, how are you doing today?
</template>
<template lwc:else>
Hi there!
</template>
</template>
In this case, the lwc:if directive checks if the userName property is equal to ‘Jack’. Here the first template will show.
If not, the lwc:elseif directive checks if the userName property is equal to ‘Rock’. Now, the second template will show.
If the first two fail, the lwc:else template is rendered.
Second One: Conditional Rendering with Loops
You can use conditional rendering with loops to display different content for each item in the loop. Let’s see the example.
<template for:each={products} for:item="product">
<div key={product.id}>
<p>{product.name}</p>
<template lwc:if={product.quantity === 0}>
<span class="sold-out">Sold Out</span>
</template>
</div>
</template>
In this example, the for:each loop iterates over the products array. For each product, the lwc:if directive checks if the quantity property is equal to 0. If it is, the “Sold Out” message is displayed.
Final One: Conditional Rendering with Forms
You can use conditional rendering to show or hide form elements based on user input.
<template>
<lightning-select value={selectedOption} onchange={handleChange}>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</lightning-select>
<template lwc:if={selectedOption === 'option2'}>
<lightning-input type="password" label="Password" required={true}></lightning-input>
</template>
</template>
In this illustration, the onchange event handler modifies the selectedOption property according to the user’s choice. Subsequently, the lwc:if directive assesses whether the selectedOption property is equivalent to ‘option2’. If true, the password field becomes visible.
These examples provide a foundational understanding of conditional rendering in LWC. This capability empowers you to craft diverse and interactive web applications with dynamic behavior.
