Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

286
Views
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>
        );
    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!