Search code examples
javascriptreactjsweb-component

how do you pass a React hook useState() 's callback function to a web component's attribute using Lit HTML


I am building a custom Web component to use with React, I am using React useState hook and I need to pass it into my custom Web Component. I know that web component attributes only take strings and if I were to stringify my function it would lose its scope. So here in lies my problem. I am Using Lit HTML and React.

    function MyReactcomp() {
       const [state, setState] = useState("");
       return (
            <div className="Wrapper">
               <customweb-component updateState={setState} />
            </div>
        );
    }

Solution

  • Try using onChange={} on your component, then create a function that will handle the change.

    
    const MyReactComp = (props) => {
      const [state, setState] = useState("");
    
      const stateUpdateHandler = (event) => {
        if ( event.target.value.trim().length > 0 ) {
          setState( event.target.value );
        }
      }
    
      return (
        <div className="Wrapper">
           <CustomWebComponent onChange={stateUpdateHandler} />
        </div>
      )
    }
    

    One of the reasons why you cannot directly use setState on the onChange={} is that the scopes are different, such that this when used within the functions may not always be at the expected scope.

    Then within your CustomWebComponet you would then pass back the value through the following:

    const CustomWebComponent = (props) => {
    
      // You can tie this is an event, or some other
      // normal function where you are processing the return value
      const onTrigger = (event) => {
        event.preventDefault();
        props.onChange(event.target.myvar.value);
      }
    
      return ( ... )
    }
    

    If you notice, the attribute name onChange={} is arbitrary and you can name it whatever you want to. Just make sure that you use the same name when you call that function, such as with the props.onChange() within the function onTrigger.