Siddharth Thakor
Siddharth Thakor

Reputation: 156

Pass @Prop() function in custom web component in stenciljs

How Can I pass @Prop() as function that toggle events for the component in Stencil.js ?

@Prop() myFunction() {
         console.log("Hello World!")
         }

and place it in

<my-component onClick={myFunction()}></my-component>

Upvotes: 2

Views: 4786

Answers (2)

Gil Fink
Gil Fink

Reputation: 787

In order to pass a function to your component you will just pass the function reference. In your example, if you exposed a myFunction Prop then all you have to do in the parent render function is to pass the function. For example:

// parent render function
render() { 
  const funcReference = () => { console.log('click') };
  return (<my-component myFunction={funcReference}></my-component>);
}

In MyComponent you will wire the function to the onClick handler of the element that should run the function. For example:

// MyComponent render function
render() {
  return (<div>
            <button onClick={this.myFunction}>Click Me!</button>
          </div>);
}

As explained by the previous answer, if you want to notify a parent component about a click then you will use an EventEmitter in the child component and a @Listen function on the parent.

Upvotes: 3

Prasheel
Prasheel

Reputation: 1020

That is not the correct way to handle events in you web component. In order to handle onClick event on your web component you must implement a click listener within your component by decorating it with @Listen decorator.

https://stenciljs.com/docs/events Events - Stencil

@Listen('click')
onClickHandler(event) {
// Do something
}

In case if you want your user to write the code for what should happen on click of your component, you need to emit the click event from your component and the user should implement a listener for that

https://stenciljs.com/docs/events Events - Stencil

Upvotes: 4

Related Questions