In Salesforce Lightning Web Components, we can apply conditional rendering, through which we can hide the elements of the LWC component or display them conditionally. To conditionally render the elements of an LWC component, we use the directives if: true and if: false.
In this Salesforce tutorial, we will learn how to implement conditional rendering in the Lightning web components.
Implement Conditional Rendering in the Salesforce Lightning Web Component
In Lightning web components, we have two key directives for applying conditional rendering.
- if:true={expression} – Renders the content inside the tag if the expression evaluates to true.
- if:false={expression}– Renders the content inside the tag if the expression evaluates to false.
These directives are used in the HTML template and depend on the properties defined in the JavaScript file.

Example-1:
In this example, we will create a Lightning web component in which a message will be shown or hidden based on a button click. In this, we add constional rendering to the LWC component using the if:true expression.
1. Create an LWC component and enter the code below in the HTML file. In this, we have defined the UI of the button and message that will be visible conditionally on button click.
<template>
<lightning-card title="Conditional Rendering Demo">
<div class="slds-p-around_medium">
<lightning-button label="Toggle Message" onclick={toggleMessage}></lightning-button>
<template if:true={isMessageVisible}>
<p class="slds-m-top_medium">This message is conditionally rendered.</p>
</template>
</div>
</lightning-card>
</template>
The directive if:true={isMessageVisible} ensures that the message inside the </p> tag only renders when isMessageVisible is true.
2. After this, enter the code below in the JS file to handle the logic to control the visibility and render it through the toggle message when conditions are true.
import { LightningElement } from 'lwc';
export default class Conditionalrenderingdemo extends LightningElement {
isMessageVisible = false;
toggleMessage() {
this.isMessageVisible = !this.isMessageVisible;
}
}
The property “isMessageVisible=false” will ensure that by default, the message will hidden and toggleMessage will display message when button is clicked.
3. After this, enter the below code in the meta.xml file to make the component visible to the Lightning pages.
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
4. Navigate to the lightning page and deploy the component. Here, you will see the button in the UI of the LWC component, a