Monday, September 12, 2022

Conditional Rendering in LWC

 

Hi Folks, In this blog we will try to understand how Conditional rendering works in LWC.

There might be a scenarios where we have to hide some content of the components from the html and show it based on conditions.

So to render html conditionally we are going to use if:true | false directive. This if:true | false directive binds the data to the template and remove or insert DOM elements based on whether the data is truthy or falsy value.

In this example, our template contains a checkbox labeled Show Candidate Details. When a user selects or deselects the checkbox, the handleChange function sets the value of the showDetails property. If the showDetails property is true, the if:true directive renders the div, which displays our candidate details.

                                    



Let's look at the code mentioned below:

conditionalRendering.html

<template>
<lightning-card title="Conditional Rendering in LWC">
<lightning-input label="Show Candidate Details" type="checkbox"
onchange={handleChange}></lightning-input>
<div if:true={showDetails}>
<p>Candidate Details:-</p>
<p>Name: Rahul Yadav</p>
<p>Age: 31</p>
<p>DOB: 15-Aug-1991</p>
</div>

</lightning-card>
</template>


conditionalRendering.js

import { LightningElement } from 'lwc';

export default class ConditionalRendering extends LightningElement {

showDetails=false;

handleChange(event){

if(event.target.checked){
this.showDetails=true;
}
}
}


Keep in mind that JavaScript only modifies a property's value rather than altering the DOM.

conditionalRendering.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>


If you have any comments or queries about this, please feel free to mention them in the comments section below.

No comments:

Post a Comment