Search code examples
polymer-3.xlit-element

Propagate a value in child components


A button toggles a boolean value in MainComp. I want to propagate the value in both the nested child components. My real project works with the first level child, it fails to update the second level child component. But oddly enough trying to replicate the code in codepen I noticed it doesn't work for the first level child either.

https://codepen.io/alfredopacino/pen/eqVGJa?editors=1001

class MainComp extends LitElement {
    constructor() {
        super()
        this.booleanValue = true
    }
    toggleBooleanValue() {
        this.booleanValue = !this.booleanValue
        this.requestUpdate();
    }
    render() {
        return html `
<style>  div {padding: 1em; border:1px solid #000} </style>
<div> main component booleanValue: ${!!this.booleanValue} <button @click=${this.toggleBooleanValue}>toggle</button>
 <child-comp ?booleanValue=${this.booleanValue}></child-comp>
</div>
`
    }
}

class ChildComp extends LitElement {
    constructor() {
        super()
    }
    static get properties() {
        return {
            booleanValue: Boolean
        }
    }
    render() {
        return html `
<style>  div {padding: 1em; border:1px solid green} </style>
<div> child component booleanValue: ${!!this.booleanValue}
<child-2-comp ?booleanValue=${this.booleanValue}></child-2-comp>
</div>
   `
    }
}

class Child_2_Comp extends LitElement {
    constructor() {
        super()
    }
    static get properties() {
        return {
            booleanValue: Boolean
        }
    }
    render() {
        return html `
<style>  div {padding: 1em; border:1px solid red} </style>
<div> child 2 component booleanValue: ${!!this.booleanValue}</div>
   `
    }
}

Solution

  • For booleanValue in MainComp to trigger a render you must either add it to MainComp's properties:

    class MainComp extends LitElement {
      static get properties() {
        return {
          booleanValue: {type: Boolean}
        }
      }
    }
    

    Note that the property is defined as {type: Boolean} and not just Boolean this is required for LitElement to know how to treat the property when doing the update

    Demo

    For more info check these two guides from the LitElement docs https://lit-element.polymer-project.org/guide/properties https://lit-element.polymer-project.org/guide/lifecycle