Search code examples
polymer-3.xlit-element

Passing a function to a child


The code is pretty straightforward: I'm try to pass the function addContactFn() from MainComp to SideMenu. On click I get the error

Uncaught TypeError: this.value.handleEvent is not a function

class MainComp extends LitElement {
    constructor(){
        super()
        this.addContactFn = this.addContactFn.bind(this)
    }
    addContactFn() {
        console.log("clicked");
    }
    render(){
        return html`
<div class="main-page">
   <side-menu addContactFn="${this.addContactFn}"></side-menu>
</div>
`
    }

}


class SideMenu extends LitElement {
    constructor(){
        super()
    }
    static get properties(){
        return {
            addContactFn: Function
        }
    }
    render(){
        return html`<a @click="${this.addContactFn}">Add contact</a>`
    }

}

Solution

  • As Thad said, attributes are always strings, and there's no real safe efficient way of parsing a function in execution

    However, you don't really even need to use that, just pass the function as a property rather than as an attribute and that should be enough, here's how MainComp's render would end up after that

    render(){
      return html`
        <div class="main-page">
         <side-menu .addContactFn="${this.addContactFn}"></side-menu>
        </div>
        `;
    }
    

    Basically, you just add a dot before the property name

    For more info check LitElement's guide

    Then again, this way of doing stuff is very React-ish and not really recommended for Web Components, you should probably just create a emit a custom event in the child component and pick it up in the parent