Search code examples
javascriptlit-element

How to send props from parent to child with LitElement


Can someone show me some simple example about sending props from parent class to child? What is the problem:

parent component:

import { LitElement, html, css } from 'lit-element';

import './child.js';

class Parent extends LitElement {
    constructor() {
        super()

        this.message = "hello world"
    }


    render() {
        return html `<child-component message=${this.message}></child-component>` //how to get this props in child component?
    }
}

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

and child component:

    import { LitElement, html, css } from 'lit-element';
    class Child extends LitElement {
      ...

      render() {
        return html `<p>${message from parent, but how}</p>` //message props should go to constructor? to render method as argument? how?
      }
    }
}
customElements.define('child-component', Child);

Solution

  • ok, I found solution. If I want to define properties in Parent class I have to add dot.

    Reference: https://lit-element.polymer-project.org/guide/properties

    render() {
        return html `<child-component .message=${this.message}></child-component>`
    }
    

    So now everything is working.

    And full example:

    parent component:

    import { LitElement, html, css } from 'lit-element';
    
    import './child.js';
    
    class Parent extends LitElement {
        constructor() {
            super()
    
            this.message = "hello world"
        }
    
    
        render() {
            return html `<child-component .message=${this.message}></child-component>`
        }
    }
    
    customElements.define('parent-component', Parent);
    

    child component:

    import { LitElement, html, css } from 'lit-element';
    
    class Child extends LitElement {
      ...
    
      render() {
        return html `<p>${this.message}</p>` //this.message have "hello world" value now
        }
    }
    
    customElements.define('child-component', Child);