Search code examples
reactjstypescriptweb-componentlit

Adding functions to lit web components in react with typescript


I have a web component i created in lit, which takes in a function as input prop. but the function is not being triggered from the react component.

import React, { FC } from 'react';
import '@webcomponents/widgets'
declare global {
    namespace JSX {
        interface IntrinsicElements {
            'webcomponents-widgets': WidgetProps
        }
    }
}
interface WidgetProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> {
    var1: string,
    successCallback: Function,
}
const App = () =>{
   const onSuccessCallback = () =>{
       console.log("add some logic here");
   }
   return(<webcomponents-widgets var1="test" successCallBack={onSuccessCallback}></webcomponents-widgets>)
}

How can i trigger the function in react component? I have tried this is vue 3 and is working as expected.

Am i missing something?


Solution

  • React does not handle Web Components as well as other frameworks (but it is planned to be improved in the future).

    What is happening here is that your successCallBack parameter gets converted to a string. You need to setup a ref on your web component and set successCallBack from a useEffect:

    const App = () => {
       const widgetRef = useRef();
       const onSuccessCallback = () =>{
           console.log("add some logic here");
       }
       useEffect(() => {
          if (widgetRef.current) {
             widgetRef.current.successCallBack = onSuccessCallback;
          }
       }, []);
       return(<webcomponents-widgets var1="test" ref={widgetRef}></webcomponents-widgets>)
    }