Usability - Productivity - Business - The web - Singapore & Twins

Using render() in LWC

Whatever template system you use, you will end up with show/hide logic based on your data's values. In Aura components you have an expression language (reminded me of JSF), in LWC external (in your JavaScript class) boolean values or functions.

Keep it tidy

A common interaction pattern, similar to the Salesforce default behavior when you have more than one record type available, is to show a pre-selection (which record type), a main selection (required data) and (eventually) a post-selection (what's next?).

In a lightning web component you can handle that easily using if:true|false inside your html template.

But what if the sections are quite lengthy? Maintaining the HTML template can get messy. Enter the render() method. In LWC this method doesn't to the actual rendering, but determines what template to use to render the component.

There are a few simple rules:

  • You need to import your template into your JavaScript file
  • The call to render() must return the imported variable (see example below)
  • You can make the computation dependent on anything inside the class
  • You can't assemble the template in memory as a String, it will throw you an error

The class file

import { LightningElement, api } from 'lwc';
import option1 from './someHTML.html';
import option2 from './anotherHTML.html';

export default class TestRender extends LightningElement {
  @api whichone = 'first';

  swapTemplate() {
    this.whichone = this.whichone === 'first' ? 'second' : 'first';

  render() {
    return this.whichone === 'first' ? option1 : option2;

The templates


  <h1>Hello World !</h1>
    label="Click me!"
    title="Template magic with John Doe"


  <h1>The second wizzard</h1>
    title="Template template on the wall"


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="TestRender">
    <masterLabel>A test of render templates</masterLabel>
    <description>Sample of the Lightning power</description>
        <targetConfig targets="lightning__RecordPage">
            <property name="whichone" datasource="first,second" type="String" default="first" />

A simple way to keep your templates tidy.
I haven't done any speed tests, so YMMV

Posted by on 04 March 2019 | Comments (0) | categories: Lightning Salesforce WebComponents


  1. No comments yet, be the first to comment