Conditional Rendering In Salesforce Lightning Web Component (LWC)

Conditional Rendering In Salesforce Lightning Web Component

Conditional Rendering In LWC

Hey Kid !! In the previous EPISODE, we discussed ways of List Iteration in Salesforce Lightning Web Component.

In this EPISODE we are going to discuss Conditional Rendering In LWC today.

What is Conditional Rendering ?
Conditional rendering means rendering a component based on a certain condition.

For Example: If you are hungry you choose to have some food. But If you are not then you will not, Right ??
Hence similar to this our component HTML template (front-end) can render or display the data based on such condition. We are going to have a live demo of this with awsome hands-on 🚗.

So let's get started......

Let's start with the syntax of the Conditional Rendering in LWC :

As we discussed the displaying of the value on the HTML template is based on the condition hence the important part to understand is the HTML template of your LWC component.

SYNTAX :
--------------------------------------------------
<template>
  <template if:true={display}>
 //Dispalying True Part
  </template>
  <template if:false={display}>
 //Dispalying True Part
  </template>
</template>
--------------------------------------------------

As you can see in the above syntax we used two more templates inside the main template. One with if:true and another template with if:false.

And the visibility of the data inside these templates depends on {display} condition. That means if the value of display is True then the true part will be visible and if value is false then the false part will be visible.

Simple right ??

Now it's time for the hands-on session to run our cool car by using this conditional rendering in LWC.

Have a look at what we are cooking today in our recipe :

Conditional Rendering In Salesforce Lightning Web Component

A cool Car which will start running on the road by switching on (true) the toggle.

Excited ??

Let's begin...

STEP 1 :
First, we need some static resources as you can see in the above snap. That you can download from the below drive link :


NOTE : Please use a Desktop or Mobile browser to open this link. (Do not click from our Android Application).

Save these three files in static resources in Salesforce Org.
with names (as I used)


STEP 2 :

Once static resources are added Open your VS Code and Authorise your salesforce org.(check the previous EPISODE for a detailed explanation on connecting salesforce org with VS Code)

and then on the left pallet, you will find the package.xml file under manifest file. 

Just right click on that and click on SFDX : Retrieve Source In Manifest From Org to retrieve all the static resources metadata from the org.

STEP 3 :

Create a new lightning web component by right-clicking on lwc folder from the left palette or by pressing CTRL+SHIFT+P (windows) or COMMAND+SHIFT+P (Mac) and run command SFDX: Create Lightning Web Component.

Give it a name called lwcConditionalRendering 

IDEA BEHIND 💡:
The idea is to create a static and non-moving car, road and wheel when the value is false.
And when the value is true based on the toggle present in the component then we will display the animated and moving car, road and wheel I used some CSS creativity here which is awesome as you will see in the output.

Go...Go...Kid 🏃‍♂️

And now just write down and understand the below code :

lwcConditionalRendering.html
--------------------------------------------------
<template>
<!--Below is the code for Toggle Switch-->
<div class="toggle">
<lightning-input
type="toggle"
label="On/Off"
name="input1"
onchange={handleChange}>
</lightning-input >
</div>
<!--Below is the template when Switch is True-->
<template if:true={isvisible}>
<!--Below code is to display moving road-->
<div class="road">
<img src={road} height="200%" width="500%">
</div>
<!--Below code is to display moving car-->
<div class="mycar">
<img src={car} height="400" width="400">
</div>
<!--Below code is to display moving wheel-->
<div class="wheel">
<img src={wheel} height="75" width="75"
class="back-wheel">
<img src={wheel} height="75" width="75"
class="front-wheel">
</div>
</template>
<!--Below is the template when Switch is False-->
<template if:false={isvisible}>
<!--Below code is to display static road-->
<div class="roadfalse">
<img src={road} height="200%" width="500%">
</div>
<!--Below code is to display static car-->
<div class="mycarfalse">
<img src={car} height="400" width="400">
</div>
<!--Below code is to display static wheel-->
<div class="wheelfalse">
<img src={wheel} height="75" width="75"
class="back-wheelfalse">
<img src={wheel} height="75" width="75"
class="front-wheelfalse">
</div>
</template>
</template>
--------------------------------------------------

lwcConditionalRendering.js
--------------------------------------------------
import { LightningElement , track} from 'lwc';
//From below three lines we imported our static resources
//With sfkidcar, sfkidcarWheel and sfkidroad label
import sfkidcar from '@salesforce/resourceUrl/sfKidCar';
import sfkidcarWheel from '@salesforce/resourceUrl/sfKidCarWheel';
import sfkidroad from '@salesforce/resourceUrl/sfKidRoad';
export default class LwcConditionalRendering extends LightningElement
{
//mapped with the HTML variables
car = sfkidcar;
wheel = sfkidcarWheel;
road = sfkidroad;
//Using track as we want to reflect the change on screen
@track isvisible;
//Below code will call when switch is on/off
//It will change the value of isvisible to true or false
//based on this isvisible value conditional rendering will display
handleChange(event) {
this.isvisible = event.target.checked;
}
}
--------------------------------------------------

And finally, create the new CSS file called lwcConditionalRendering.css under the same component folder hierarchy as below.

lwcConditionalRendering.css
--------------------------------------------------
.toggle{
position:absolute; right:80%;
}
.road{
width: 200%;
position: absolute;
bottom: 0;
right: 0;
left: 0;
z-index: 1;
top: 79%;
animation: road 5s linear infinite;
}
@keyframes road{
100%{
transform: translateX(-1400px);
}
}
.mycar img{
position: absolute;
top: 41%;
left: 34%;
animation: car 1s linear infinite;
}
@keyframes car{
100%{
transform: translateY(-1px);
}
50%{
transform: translateY(2px);
}
0%{
transform: translateY(-1px);
}
}
.wheel{
left: 50%;
bottom: 178px;
transform: translateX(-50%);
position: absolute;
z-index: 2;
}
.wheel img{
animation: wheel 1s linear infinite;
}
@keyframes wheel{
100%{
transform: rotate(360deg);
}
}
.back-wheel{
position: relative;
right: 129px;
top: 129px;
}
.front-wheel{
position: absolute;
right: -116px;
top: 129px;
}
/* below css are for false part */
.roadfalse{
width: 200%;
position: absolute;
bottom: 0;
right: 0;
left: 0;
z-index: 1;
top: 79%;
}
.mycarfalse img{
position: absolute;
top: 41%;
left: 34%;
}
.wheelfalse{
left: 50%;
bottom: 178px;
transform: translateX(-50%);
position: absolute;
z-index: 2;
}
.back-wheelfalse{
position: relative;
right: 129px;
top: 129px;
}
.front-wheelfalse{
position: absolute;
right: -116px;
top: 129px;
}
--------------------------------------------------

NOTE: Please notes that the above CSS positions of the images are adjusted as per my MacBook screen size. hence please adjust the positions of the car, wheel or road.

All code snippets are easily understandable with the help of code comments added. 😊

And finally its time for Output preview : 
I am using local development for preview as discussed in the previous episodes. You can also see preview by adding this component to lightning application and deploying it to production.

If You have setup the Local Development then right-click on your lwc component and select SFDX: Preview Component Locally.

And its time to check our cool output with conditional rendering in salesforce lightning web component.

PREVIEW OUTPUT :
--------------------------------------------------

--------------------------------------------------

Aweesommmm ⚡️.......Car, road and wheels are moving when you turn on the toggle.
And if you Turn Off the toggle then it stops moving.

Coool...I hope you definitely liked this one....Now it's time to create it on your own and show it off to all your friends. Don't forget to tag me 😁.

In the Next EPISODE, we will discuss Lightning Web Component Compositions...So stay tuned...

WOHOOO !! YOU HAVE JUST COMPLETED CONDITIONAL RENDERING IN LIGHTNING WEB COMPONENT (LWC) EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all
Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊 

<< PREVIOUS                                  NEXT >>

Conditional Rendering In Salesforce Lightning Web Component (LWC) Conditional Rendering In Salesforce Lightning Web Component (LWC) Reviewed by on Rating: 5

9 comments:

  1. Hello I tried your code but I am not able to deploy it because of this error - Invalid reference sfKidCarWheel.png of type resourceUrl in file lwcConditionalRendering.js

    I retrieved from amnifest and can see these 3 resources in staticResources folder but I am not sure how to solve this error. Please let me know. Thanks!

    ReplyDelete
    Replies
    1. Ideally It should not give you that error !! I have re-checked code from my end and its working fine for me.
      Please try to debug or write us at www.salesforcekid1@gmail.com for more assistance.

      Thanks 😊

      Delete
    2. thanks for the blog it is awesome. I got the error similar to mentioned above but it is fixed by removing .png from resources in JS file .. use it like below
      import sfkidcar from '@salesforce/resourceUrl/sfKidCar';

      Delete
    3. Hey Lalit! Thanks for the update. I have updated the same in the snippet code above. I hope this will work perfectly fine now.

      ⚡️HAPPY LEARNING ⚡️

      Delete
  2. Love reading your blogs, thanks for sharing such an informative article
    Salesforce Development Support

    ReplyDelete
  3. i am unable to view manifest file

    ReplyDelete
    Replies
    1. you do not need specific manifest file for this

      Delete
  4. Anonymous2/17/2022

    Nice post, thanks for sharing this valuable information.

    salesforce development company
    drupal development company

    ReplyDelete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.