Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

114
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>
        );
    }
7 months 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.

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.