
Conditional rendering in LWC enables you to dynamically display or hide content based on certain conditions.
New Directive In LWC:
With Spring’23, Salesforce introduced new directives for conditional rendering: lwc:if, lwc:elseif, and lwc:else. These are preferred over the older if:true|false.
First One: Simple Conditional Rendering
Here’s a snippet to demonstrate showing different greetings based on a user’s name:
Hi Jack, welcome back!
Hello Rock, how are you doing today?
Hi there!
Here, lwc:if checks if userName is ‘Jack’. If true, the first template appears.
Otherwise, lwc:elseif checks if userName is ‘Rock’. If true, the second template appears.
If neither, lwc:else is rendered.
Second One: Conditional Rendering with Loops
Conditional rendering can be used within loops to show different content for each item. Here’s an example:
{product.name}
Sold Out
In this case, the for:each loop goes through the products array. If a product’s quantity is 0, it shows “Sold Out”.
Final One: Conditional Rendering with Forms
Conditional rendering can toggle form elements based on user input:
Option 1
Option 2
Here, the onchange event handler alters the selectedOption based on user selection. If selectedOption is ‘option2’, the password field appears.
These examples show the basics of conditional rendering in LWC, enabling various dynamic and interactive web applications.
Resources:
<a href="https://developer.salesforce.com/blogs/2023/01/lwc-enhancements-for-developers-learn-moar