Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

287
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda