
Conditional rendering in LWC lets you dynamically toggle content visibility based on specific conditions.
New Directive In LWC:
Starting Spring’23, Salesforce introduced new directives for conditional rendering: lwc:if, lwc:elseif, and lwc:else, which are recommended over the legacy if:true|false.
First One: Simple Conditional Rendering
This example shows how to display different greetings based on the user’s name:
Hi Jack, welcome back!
Hello Rock, how are you doing today?
Hi there!
The lwc:if directive checks if userName equals ‘Jack’. If true, it shows the first template.
If not, lwc:elseif checks if userName equals ‘Rock’. If true, the second template shows.
If both conditions fail, the lwc:else template renders.
Second One: Conditional Rendering with Loops
Use conditional rendering with loops to display specific content for each item. See the example:
{product.name}
Sold Out
The for:each loop iterates over the products array. The lwc:if directive checks if quantity is 0 to display “Sold Out”.
Final One: Conditional Rendering with Forms
Conditional rendering can show or hide form elements based on user input.
Option 1
Option 2
The onchange event updates the selectedOption property. The lwc:if then checks if selectedOption is ‘option2’ to display the password field.
These examples showcase basic conditional rendering in LWC, enabling the creation of dynamic and interactive applications.
Resources:
<a href="https://developer.salesforce.com/blogs/2023/01/lwc-enh