Search code examples
lit-element

Rendering one of multiple pages with lit-element


The lit-element documentation describes conditional rendering via (condition ? a : b). I was wondering how to use that to render one of multiple pages, f.e. in combination with mwc-tab-bar from Googles material web components.

My current solution is something like this:

render() {
    ... other stuff ...

    ${this.selectedPage === 0 ? html`
    <div>
        ...
    </div>
    ` : html``} 

    ${this.selectedPage === 1 ? html`
    <div>
        ...
    </div>            
    ` : html``}     

    ... further pages ... 
}      

I don't like the :html`` part but is that how it's meant to be?


Solution

  • Use more simple code like this.

    constructor(){
        super();
        // don't forget add `prop` and `selectedPage` to `static get properties()`
        this.prop = 1;
    }
    render() {
        return this.getPage(this.selectedPage);
    }
    
    getPage(num){
        switch(num){
            default:
            case 1:
                return html`<div>P${this.prop}<div>`;
            case 2:
                return html`<div>P2<div>`;
        }
    }