Render is mainly used to conditionally render a template. It defines the business logic to decide which template (HTML file) to use.
Enter the render() method
In LWC this method doesn’t do the actual rendering, but determines what template to use to render the component.
There are a few simple points:
- We need to import the template into the JavaScript file
- The call to return must return the imported variable
Use Case: We have a salesTemplate and on click of which we are able to redirect to service template.
In this use case we have following file structure:
- salesTemplate.html
- serviceTemplate.html
- salesTemplate.js
If you observe, we have two templates and we are conditionally rendering them based on the component’s state.
Code Snippet.
salesTemplate.html
<template> <lightning-card title="Example of render() lifecycle hook"> This is the Sales Template <br/> <br/> <lightning-button label="Go to the service template" onclick={onchange}> </lightning-button> </lightning-card> </template>
salesTemplate.js
import { LightningElement } from 'lwc'; import firsttemplate from './salesTemplate.html'; import secondtemplate from './serviceTemplate.html'; export default class SalesTemplate extends LightningElement { templatename = 'Salestemplate'; constructor(){ super(); console.log("Inside Constructor- salestemplate"); } connectedCallback(){ console.log("Inside ConnectedCallback -salestemplate"); } onchange(){ if (this.templatename === 'Salestemplate' ) { this.templatename = 'Servicetemplate'; } else{ this.templatename = 'Salestemplate'; } } render(){ console.log("Inside render") if (this.templatename === "Salestemplate") { console.log("Inside render -salestemplate") return firsttemplate; } else{ console.log("Inside render -servicetemplate") return secondtemplate; } } renderedCallback(){ console.log("renderedcallback"); } }
serviceTemplate.html
<template> This is service template; </template>
Demo
Understanding Code Line by Line:JS
import firsttemplate from './salesTemplate.html'; import secondtemplate from './serviceTemplate.html';
onchange(){ if (this.templatename === 'Salestemplate' ) { this.templatename = 'Servicetemplate'; } else{ this.templatename = 'Salestemplate'; } }
render(){ if (this.templatename === "Salestemplate") { console.log("Inside render -salestemplate") return firsttemplate; } else{ console.log("Inside render -servicetemplate") return secondtemplate; } }
I hope you enjoyed the chapter !
Together we can learn faster !
Join LWC study group on Telegram
Subscribe to Youtube channel and blog to get latest updates
Reference