Conditional rendering of different html file in Lightning Web Component

Lightning web component allows you to conditional rendering of html files based on device width. According to docs, For complex tasks like conditionally rendering a template or importing a custom one, use render() to override standard rendering functionality. This function gets invoked after connectedCallback() and must return a valid HTML template.

Component Design

We have a lightning web component with two extra html file. Our aim is to conditional rendering the file based on the device width. Whenever the component gets rendered on mobile devices, smallScreen.html file gets rendered. Similarly, when you see the same component on large screen devices, largeScreen.html file will get rendered.

Code

renderHtml.html

This file contains blank template. We do have two other html file in the component folder which will render based on device width.

<template>
    
</template>

renderHtml.js

The javaScript file contains render() method which is a part of life cycle hooks. As per the code below, method return the imported html file based on device width.

import { LightningElement } from "lwc";
import smallScreen from "./smallScreen.html";
import largeScreen from "./largeScreen.html";

export default class RenderHtml extends LightningElement {
  render() {
    return window.screen.width < 768 ? smallScreen : largeScreen;
  }
}

renderHtml.js-meta.xml

The configuration file defines the metadata values for the component, including the design configuration for Lightning App Builder and Community Builder. In simple words, It defines where you can use the component in Lightning Experience.

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

smallScreen.html

This file will get conditionally rendered based on device width.

<template>
  This is small Screen
</template>

largeScreen.html

This file will get conditionally rendered based on device width.

<template>
This is large Screen
</template>

Demo(Conditional rendering of html files based on device width)

If you open the component in mobile, It says ‘this is small screen’ as smallScreen.html got rendered.

small screen device

If you open the component in desktop, It says ‘this is large screen’ as largeScreen.html got rendered.

large screen device

Leave a Reply