Multipage LWC Component Using Render() Method
Whenever the developer develops the multi page component along with them, they create a separate child component. While creating the child component, it took a long time to load all the functionality. In that situation, we go to the “render()” methods in LWC to avoid the slow process while loading the multiple components.
The render() method runs whenever the event action happens. We also use this to render multiple pages.
Create Lightning Web Component
- Let’s create a multi page component. Here we create three pages.
parent.Html
<template>
<lightning-card title="Multipage Components">
<h1 data-id='heading'>Home page</h1>
<lightning-button label={PageLabel} onclick={onchange}>
</lightning-button>
</lightning-card>
</template>
- This is the child page file. From here we go to page No.3.
child.Html
<template>
<lightning-card>
<h1>Child Page</h1>
<lightning-button label={PageLabel} onclick={onchange}>
</lightning-button>
</lightning-card>
</template>
- Subchild page .we create number files like as per your requirement.
subChild.Html
<template>
<lightning-card>
<h1>subChild Page</h1>
</lightning-card>
</template>
- We use single js file for all pages. We create more than one js file but all the child HTML files will get the data from parent js file. If you want use child js files then we can export and import from parent file.
Parent.JS
import { LightningElement } from 'lwc';
import firsttemplate from './parent.html';
import secondtemplate from './child.html';
import thirdtemplate from './subChild.html';
export default class parent extends LightningElement {
templatenumber = 'temp1';
PageLabel='Go to Page2'
onchange(){
if(this.templatenumber==='temp1'){
this.templatenumber='temp2';
this.PageLabel='Go to Page3'
}
else if(this.templatenumber==='temp2'){
this.templatenumber='temp3';
}
else if(this.templatenumber==='temp3'){
this.templatenumber='temp3';
}
}
render(){
console.log('Inside render');
if(this.templatenumber==='temp1'){
return firsttemplate;
}
else if(this.templatenumber==='temp2'){
return secondtemplate;
}
else if(this.templatenumber==='temp3'){
return thirdtemplate;
}
}
}
Parent.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle
xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__Tab</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
- Finally run the component and test it.
When we click Go to Page2 button it will get redirect to page2.
After clicking Go to Page3 button it will get redirect to page3.