Saif Farooqui
Saif Farooqui

Reputation: 150

Calling React function from stencil web component

This is my react functional component

const goTo = () => {
    console.log("This method call.");
  };
return (
    <div>
      <div className="container">
        <otp-web-component
        callBack={() => goTo}>
        </otp-web-component>
      </div>
    </div>  
)

This is stencil component

    @Component({
      tag: "otp-web-component",
      styleUrl: "my-component.css",
    })
    export class otpcomponent {
    @Method() CallBack:()=>void; //calling this on button click
    
       @Listen("event.keydown.enter")
      goBack() {
   //  calling callback function here
       }
        render(){
          return(
           <button
              class="btn btn-primary"
              style={buttonStyle}
              onClick={this.goBack.bind(this)}
              >
               get
             </button>
          )
        }

When clicking on get button in stencil component it should execute the react function goTo();

Upvotes: 1

Views: 1733

Answers (1)

Simon H&#228;nisch
Simon H&#228;nisch

Reputation: 4968

Just listing some things that look wrong and might help you figure out what the problem is:

  1. You're using the @Method decorator for CallBack but you're not defining a method. You probably want to use the @Prop decorator. It's possible to pass a function (or any JS object) as a prop. You can read about the method decorator here: https://stenciljs.com/docs/methods.
  2. When using your component in React, you're not actually calling the goTo function. You're passing a function that returns the goTo function instead because you forgot the (). You either want to use callBack={goTo} or callBack={() => goTo()}.
  3. You've defined your prop (the one with the @Method decorator) as CallBack (pascal case) but then you're using it as callBack (camel case). Stencil component property names are not case insensitive.
  4. @Listen("event.keydown.enter") this is not how you bind an event listener to a keyboard event. See https://stenciljs.com/docs/events#keyboard-events.

So, I think your component should look sth like this (simplified):

@Component({ tag: 'otp-web-component' })
export class OtpWebComponent {
  @Prop() callback: () => void;

  goBack = () => {
    // ...
    this.callback();
  }

  render() {
    return <button onClick={this.goBack}>Click me</button>;
  }
}

and then you can use it like

export default () => {
  const goTo = () => console.log('I got called');

  return <otp-web-component callback={goTo} />;
}

Upvotes: 0

Related Questions