Search code examples
javascriptweb-componentlit-elementlit-html

Component not re-rendering when calling function from child


I am trying to change the property by calling the parent function from the child. Here is the link to an example. I assume that the property change triggers re-render when the function called from the event i.e. @click. But is it possible to change the property and trigger re-render by passing the function to the child and calling it?

class ParentComponent extends LitElement {

      static get properties() {
        return {
          value: { type: String, reflect: true }
        }
      }

      constructor() {
        super();
        this.value = 'value';
      }

      handleClick(value) {
        this.value = value;
      }

      render() {
        return html `
          <div>
            <p>My Value: ${this.value}</p>

          <button @click="${() => this.handleClick('value from parent')}">Parent Button</button>
            <child-component
              .handleClick="${this.handleClick}"
            ></child-component>
          </div>
        `;
      }

    }

 customElements.define('parent-component', ParentComponent);

 class ChildComponent extends LitElement {

      static get properties() {
        return {
          handleClick: { type: Function }
        }
      }

      render() {
        return html `
          <button @click="${() => this.handleClick('value from child')}">Child Button</button>
        `;
      }

    }

customElements.define('child-component', ChildComponent);

Solution

  • When the child button is clicked handleClick has a this context of the ChildComponent. If you update the ParentComponent template with an => function the new value gets set on the ParentComonent.

    <child-component
      .handleClick="${(value) => this.handleClick(value)}"
    ></child-component>