-1

how to write below code lit html

I am new to lit html , i try to convert the below code to if/else instead of nested ternary

 render() { 
    return this.html`   
     ${this.data ? this.html`<comp data={this.data}></comp>`
                    : data1 && data1.test === 'valid' && valueCheck ? this.html`
                      <comp2 data={this.data2}  ></comp2>
                    `
                    : this.html`
                      <comp1 data={this.data1}  ></comp1>
                    `} `;}

Need to convert simple if else

John Ken
  • 898
  • 1
  • 13
  • 26

2 Answers2

1

I understand you want to use this to render components. Normally, when I have complex validations if/elses to do, I do them outside the render part and attribute it to a variable.

let dataToRender = undefined;
if(this.data){
    dataToRender = this.html`<comp data={this.data}></comp>`
} else if(data1 && data1.test === 'valid' && valueCheck){
    dataToRender = <comp2 data={this.data2}  ></comp2>
} else {
    dataToRender = <comp1 data={this.data1}  ></comp1>
}

And, then, on the render function simply:

render(
    ${dataToRender}
)
Pelicer
  • 1,348
  • 4
  • 23
  • 54
1

You usually want to enumerate the value based on the logic, it's more readable and maintainable in the future if your logic grows.

You can also combine the built-in choose directive to render one of many templates based on the key value.

import { LitElement, html } from "lit";
import { choose } from "lit/directives/choose.js";

enum RenderOptions {
    COMP,
    COMP_1,
    COMP_2
}

class MyElement extends LitElement {
    // mocks
    data = {}
    data1 = { test: "valid" }
    data2 = {}
    valueCheck = true

    render() {
        return html`
            ${choose(this._conditionalRender(), [
                [RenderOptions.COMP, () => html`<comp data={this.data}></comp>`],
                [RenderOptions.COMP_1, () => html`<comp1 data={this.data1}></comp1>`]
                [RenderOptions.COMP_2, () => html`<comp2 data={this.data2}></comp2>`],
            ],
            () => html`<h1>Error</h1>`)}
        `;
    }

    private _conditionalRender(): RenderOptions {
        if (this.data) {
            return RenderOptions.COMP
        }
        if (this.data1 && this.data1.test === 'valid' && this.valueCheck) {
            return RenderOptions.COMP_2
        }
        return RenderOptions.COMP_1
    }
  }


// implementations of...
// comp
// comp1
// comp2
Filip Seman
  • 1,252
  • 2
  • 15
  • 22