Render DOM Elements Conditionally
The legacy if:true and if:false directives are no longer recommended. To future-proof your code, replace them with the lwc:if|elseif|else conditional directives.
Directives are special HTML attributes that let you manipulate the DOM using markup. To render different HTML depending on a {property}, add conditional directives to a tag that encloses your conditional content.
Lightning Web Components supports the conditional directives lwc:if={property}, lwc:elseif={property}, and lwc:else. The lwc:if|elseif directives bind {property} to the template, removing and inserting DOM elements based on whether the data is a truthy or falsy value.
You can use conditional directives on nested <template> tags and HTML standard tags such as <div>. You can also use conditional directives with your custom component tags like <c-custom-cmp> or base component tags like <lightning-spinner>.
For a full list of guidelines for conditional directive usage, see HTML Template Directives: lwc
The following example has two properties: property1 and property2.
Only one of the three statements renders based on this logic:
Statement1renders ifproperty1is true.Statement2renders ifproperty1is false andproperty2is true.Statement3renders ifproperty1andproperty2are false.
Although the example uses all three directives, lwc:elseif and lwc:else are optional.
Let’s look at another example. This template contains a checkbox labeled Show details. When a user selects or deselects the checkbox, the handleChange function sets the value of the areDetailsVisible property. If the areDetailsVisible property is true, the lwc:if directive renders the nested template, which displays These are the details!.
Notice that the JavaScript doesn’t manipulate the DOM, it simply changes the value of a property.


To toggle the value of a boolean property in markup, default the value to false. See Boolean Properties.
This sample code is the helloConditionalRendering component from the github.com/trailheadapps/lwc-recipes repo. For an example that uses a conditional directive on an HTML element, such as a div element, see the helloIterator component.
You can nest conditional statements within one another to create complex custom logic. For example, the following code checks if a user is logged in, and if they are, it subsequently checks if they have new notifications.
You can nest conditional directives inside components. In this example, if property1 is true, <c-child-1> is rendered inside <c-parent>. If property1 is false and property2 is true, <c-child> renders <c-child-2> instead.
However, preceding lwc:elseif or lwc:else with text or another element isn't allowed. The following sample code throws an error because the lwc:elseif directive must be used immediately after an element with lwc:if or lwc:elseif.
See Also