Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

291
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda