Sub topic 4
render(): choosing which template to show
This chapter assumes you can write a Lightning Web Component with an HTML template and a JavaScript class, and that you know reactive properties and template expressions. It covers how render() fits into the lifecycle and how to use it to switch between templates.
Where render() fits
After connectedCallback() runs, the engine needs a template to turn into DOM. It gets that template by calling the component's render() method. Every component has this method. If you don't write one, the default render() returns the template file with the same name as the component, such as greeting.html for a component called greeting.
You override render() when one component needs more than one template. The method returns a template that you imported from an HTML file. It does not return a string or DOM nodes.
Overriding render()
Put each template in its own HTML file in the component folder. Import each file as a module, then return the one you want.
import { LightningElement } from 'lwc';
import signedInTemplate from './signedIn.html';
import signedOutTemplate from './signedOut.html';
export default class Greeting extends LightningElement {
isSignedIn = false;
render() {
return this.isSignedIn ? signedInTemplate : signedOutTemplate;
}
}The two template files sit next to greeting.js. A component folder like this is valid:
greeting/greeting.jsgreeting/signedIn.htmlgreeting/signedOut.html
When you override render(), the engine no longer looks for greeting.html. Each imported template is a normal LWC template, so it can use {expressions}, lwc:if, and child components.
When render() runs again
render() runs before the first render, and it runs again each time the component re-renders. A re-render happens when a reactive value that the current template uses changes. The isSignedIn field in the example is not read by either template. It is read inside render() itself, and the engine tracks reads that happen there too. So changing isSignedIn makes the engine call render() again, and it can switch templates.
If the new call returns the same template as before, the engine reuses the existing DOM and updates it. If it returns a different template, the engine replaces the old template's DOM with the new one. That replacement has two consequences:
- Child components in the old template are removed, so their
disconnectedCallback()runs. Children in the new template are created from scratch. - Local state inside those children, such as typed text in an input, is lost.
Because of this, switch templates for large structural changes, such as sign-in versus sign-out views. For small differences, such as showing or hiding one element, use lwc:if in a single template. It is simpler and keeps the surrounding DOM.
Rules for render()
- Return only a template imported from an HTML file, or a template that the compiler produced. Returning anything else raises an error.
- Keep it fast and free of side effects. It can run many times, so don't fetch data, set fields, or touch the DOM inside it.
- Don't assign to a reactive field in
render(). A change there schedules another render, which can cause a loop. - Don't read the rendered DOM from
render(). The new DOM doesn't exist yet. UserenderedCallback()for that.
Styles follow the template
CSS is tied to the template. A stylesheet named after the component, such as greeting.css, applies to all templates of that component. To give one template its own styles, add a CSS file with the same base name as that template (signedIn.css for signedIn.html) and import it from the template.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Returning a string such as `'signedIn'` | The engine throws an error because it expects a template | Import the HTML file and return the import |
| Fetching data in `render()` | Repeated requests on every render | Fetch in `connectedCallback()` |
| Using separate templates for a small toggle | Child state is lost on every switch | Use `lwc:if` in one template |
| Leaving out a template import | The component fails to compile | Check that each file exists in the component folder |
Summary of behavior
- The engine calls
render()once afterconnectedCallback()and before the first render. - The method returns an imported template.
- When tracked values change, the engine calls
render()again. - A different template replaces the DOM. The same template updates it in place.
renderedCallback()runs after each render finishes.
Exercise
A component imports listView.html and tableView.html and returns one of them from render() depending on a viewMode field. Users report that text typed into an input inside the list view disappears whenever viewMode changes and then changes back. Why does this happen, and when would you choose lwc:if instead?
Show answer
Changing viewMode makes render() return a different template, so the engine replaces the old template's DOM. The input and any children in it are removed and later created again, which loses their local state. If the two views differ only in a small part of the markup, use lwc:if in one template. The shared DOM is then kept and its state survives.
Exercise
Why should render() not fetch data or assign to reactive fields?
Show answer
render() can run on every re-render. A fetch would repeat each time, and assigning to a reactive field schedules another render, which can cause a loop. Put one-time setup in connectedCallback().