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.



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



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;


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="" fqn="renderHtml">


This file will get conditionally rendered based on device width.

  This is small Screen


This file will get conditionally rendered based on device width.

This is large Screen

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


  1. Why do we need the blank html file renderHtml.html ? I think this whole thing works even if that file is deleted from the bundle. Just the other two html files are needed.

Leave a Reply