Using If and Else – Lightning Web Components ( With Tom & Jerry )
Objective
Learn about rendering DOM using if and else. (render elements dynamically)
In this unit, we will be learning that how can we use if and else to show/hide the html in lightning web components. To understand that we will be creating very simple app called Tom & Jerry.
App Description:
The requirement is that only one can be present in the salesforce org at a time. Either it can be Tom or Jerry. It will be very simple app. We are not going to write interstellar space theory. Kidding!!
Create Lightning Web Component Bundle:
1. Open Visual Studio Code.
2. Press Command+Shift+P (Mac), Ctrl+Shift+P( Windows)
3. Here type SFDX: Create Lightning Web Component
4. It will ask for the desired directory, Just press enter
5. Give the name to your Lightning Web Component as TomAndJerry and press enter.
6. This will create a folder structure for the TomAndJerry.
If-Else Explanation or Render Elements Dynamically:
I believe that you must have worked on either visualforce pages or lightning components. Let’s see how we handle these things in visualforce and lightning components.
Lightning Component:
Visualforce:
Lightning Web Component: In LWC, It is more nearer to the Visualforce but it doesn’t support ! (Not). Instead of this we check using if:false. If you use ! (Not) then you will get error while saving.
Code time: Copy the below code to the newly created files in LWC bundle.
Note: To see tom and jerry both, You need to change the showTom variable value to true or false and need to push it scratch org.
Deploy the Code to Scratch Org:
Open Visual Studio Code’s Integrated Terminal.
Type below command and hit the enter.
sfdx force:source:push
Add Lightning Web Component to Lightning Home Layout:
1. Open any app in lightning and go to the home tab.
2. Click on Gear Icon (Top-Right) and then click on Edit Page.
3. Here in the left side, Scroll down to Custom section.
4. Drag TomAndJerry component to the home layout.
5. Click on Save and Activate.
6. After successful activation. Go back to the Home tab.
Cheers!!
Read more blogs on Lightning Web Components here…
Suggestion: Just make sure that you add the @track decorator to the `showTom` field in your class. As a general rule, if you use a field in your template, you should track it in your class, so if its value changes, the DOM gets updated automatically.
Thank You for the suggestion. I didn’t put it purposefully. As beginners may get confused what are @track and @api. To keep the simple i just introduced only if else in the blog. Javascript properties will be covered in the next blogs.