Conditional Rendering in LWC

Conditional Rendering in LWC

2 Min Read

Conditional rendering in LWC lets you dynamically show or hide content based on specific conditions.

New Directive In LWC:

From Spring’23, Salesforce introduced new directives for conditional rendering: lwc:if, lwc:elseif, and lwc:else. These are recommended over the legacy if:true|false.

First One: Simple Conditional Rendering

This snippet demonstrates displaying different greetings based on the 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 not, lwc:elseif checks if it is ‘Rock’. If both conditions fail, the lwc:else template renders.

Second One: Conditional Rendering with Loops

Use conditional rendering with loops to display different content for each loop item. Consider this example:

  

{product.name}

Sold Out

In this example, the for:each loop iterates over the products array. lwc:if checks if quantity is 0, displaying “Sold Out” if true.

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 selectedOption. The lwc:if directive checks if selectedOption is ‘option2’, displaying the password field if true.

These examples show basic conditional rendering in LWC, which can create dynamic web applications.

Resources:

Salesforce release note

You might also like