How to perform conditional rendering in LWC?

Conditional rendering is a technique for displaying components or elements based on a predetermined condition. For example, conditional rendering is used if you want to display different messages at different times. We can render different LWC components or elements if a condition using conditional rendering in LWC is met.

In today’s blog, we will show you how to use conditional rendering in the lightning web component.

So, Let’s begin!

conditionalRendering.html

The ConditionalRendering class sets the value of the is SystemAdministrator property when a page loads.

If the is SystemAdministrator property is true, the if: true directive displays the nested template. You are now a System Administrator!

If the is SystemAdministrator property is false, the if: true directive displays the next nested template. You have successfully registered as a Business User!

Code

conditionalRendering.js

We are not manipulating the DOM in this JavaScript; instead, we are importing the profile name from Salesforce and changing the value of the is SystemAdministrator property.

Code

conditionalRendering.js-meta.xml

This configuration file makes the component available for all Lightning page types except the home page, which is only supported on desktops.

Code

Output:

  • if a User with a profile System Administrator loads the home page, the lightning web component will display the following message.
  • if a User with a profile other than System Administrator loads the home page, the lightning web component will display the following message.

Conclusion

We hope you find the tutorial helpful. Feel free to use the code to implement conditional rendering in LWC.

Also, stay hooked to our tutorials as we will be back with another interesting Salesforce development solution soon. Catch you on the next one, Happy Coding!!

Our Location worldwide
India
3rd Floor, A-10, Pegasus Tower, Sector 68, Noida, Uttar Pradesh 201301 +91-1203117884
SR Tower 2nd Floor Hydel Gate Haldwani Uttarakhand 263126 +91-5946359996
USA
333 West Brown Deer Road Unit G – 366 Milwaukee WI, USA 53217 +1(262) 310-7818
UK
7 Bell Yard, London, WC2A 2JR +44 20 3239 9428
Canada
HIC Global Solutions INC
43 Lafferty Lane, Richmond Hill, L4C 3N8, CA +1(262) 310-7818