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
someHTML.html
<template>
<h1>Hello World !</h1>
<lightning-button
accesskey="k"
onclick={swapTemplate}
variant="brand"
label="Click me!"
title="Template magic with John Doe"
></lightning-button>
</template>
anotherHTML.html
<template>
<h1>The second wizzard</h1>
<lightning-button
accesskey="k"
onclick={swapTemplate}
variant="success"
label="Back"
title="Template template on the wall"
></lightning-button>
</template>
js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="TestRender">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>A test of render templates</masterLabel>
<description>Sample of the Lightning power</description>
<targets>
<target>lightning__RecordPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<property name="whichone" datasource="first,second" type="String" default="first" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
A simple way to keep your templates tidy.
I haven't done any speed tests, so YMMV
Posted by Stephan H Wissel on 04 March 2019 | Comments (3) | categories: Lightning Salesforce WebComponents