Bluecloud

Bluecloud

How to use multiple views in single LWC component.

Frontend

Sometimes we need to use multiple views in a single Lightning Web Component. Lightning fraemwork allows us to do such decomposition. In this guide I will show you how to split one big html component into separate small ones.

file structure:

multipleViewComponent
    ├── multipleViewComponent.css
    ├── multipleViewComponent.js
    ├── multipleViewComponent.js-meta.xml
    ├── viewOne.html
    ├── viewThree.html
    └── viewTwo.html

multipleViewComponent.js

import { LightningElement, api } from 'lwc';

//importing our views
import viewOne from './viewOne.html'
import viewTwo from './viewTwo.html'
import viewThree from './viewThree.html'

//importing shared css
import css from './multipleViewComponent.css';

export default class MultipleViewComponent extends LightningElement {
    @api displayType;

    views = {
        'one' : viewOne,
        'two' : viewTwo,
        'three' : viewThree,
    };

    //This should be done to apply one css file to multiple html views.
    static stylesheets = [
        css
    ]

    //We need to override this function it should return html view.
    render() {
        return this.views[this.displayType];
    }
}

multipleViewComponent.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>57.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <property name="displayType" label="Display Type" type="String"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

multipleViewComponent.css

.one {
    background-color: white;
    height: 100px;
    width: 100px;
}

.two {
    background-color: red;
    height: 100px;
    width: 100px;
}

.three {
    background-color: white;
    height: 100px;
    width: 100px;
}

viewOne.html

<template>
    <div class="one">ONE</div>
</template>

viewTwo.html

<template>
    <div class="two">TWO</div>
</template>

viewThree.html

<template>
    <div class="three">THREE</div>
</template>

As you can see we added an @api variable to catch a value from the component settings page and we have the object views that stores key=value pair, the key is name that will be passed from the outside and the value is imported view from the component.

views = {
        'one' : viewOne,
        'two' : viewTwo,
        'three' : viewThree,
    };

You are able to to set value in this way:

Option 1

Or even this:

Option2

Result when option “two” was selected on the component setting page:

Option two was selected