Visualforce to LWC: Conditional Rendering

Hello Ohana,

Welcome back to the Visualforce to LWC series. In this article I will be discussing Conditional Rendering and how to build an awesome Lightning Web Component using it. Let’s first explain what is Conditional Rendering and how we used to deal with it in Visualforce.

Conditional Rendering is used to show or hide a particular block based on a condition. If you take a look at the below example you’ll see that we are using the checkbox to control whether or not to display the text: Egypt.

Conditional Rendering in LWC:

To be able to use conditional rendering in lightning you need a new nested template tag with the directive if:true or if:false. It sounds more complicated but I promise you it’s a whole lot easier.

Let’s take a look at the same example done with a lightning component:

Line 3: We use a lightning-input component of the type checkbox. The lightning-input component also supports other types like ( text, date, datetime, url ) but for the purpose of this example we are using the checkbox type. In the onchange attribute we specify a function that triggers when a change in the checkbox occurs.

Line 3–6: We are telling the component to show the text between the template tag if the variable displayCountry is true. The text between the template tag in this case is Egypt.

Line 7–9: We are telling the component to show the text between the template tag if the variable displayCountry is false.

Line 4: We define a boolean variable called displayCountry.

Line 5–6: This is the function that we called in line 3 on the HTML file. This function is called whenever a change happens to the checkbox, and by “change” I mean if the checkbox is checked or unchecked by the user. Inside the function, we capture the change in the variable we defined: displayCountry.

displayCountry is true if the checkbox is checked and false if not.

To learn more about conditional rendering check the Component Documentaion.

Happy Learning :)!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store