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

218
Visualizações
Type 'string' is not assignable to type 'HTMLInputElement'

I am having a form in React TypeScript which looks like this:

<form onSubmit={handleSubmit}>
    <input type="text" className="form-control" ref={firstName} name="firstName" id="firstName"/>
    <input type="text" className="form-control" ref={lastName} name="lastName" id="lastName"/>
</form>


const handleSubmit = e => {
    e.preventDefault();
    const data = {
        firstName: firstName.current.value,
        lastName: lastName.current.value,
    }
    let formdata = JSON.stringify(data);
    history.push({
        pathname: '/review',
        state: { details: formdata }
    });
}
const firstName = React.useRef(null);
const lastName = React.useRef(null);

This works fine as we are getting empty values in firstName and lastName of the field. But when I change it to:

const firstName = React.useRef(SomeObject.name);

And remove the value inside the handleSubmit method,

const handleSubmit = e => {
      e.preventDefault();
      const data = {
         firstName: firstName.current,   <-- Change here
         lastName: lastName.current.value,
      }
      let formdata = JSON.stringify(data);
      history.push({
          pathname: '/review',
          state: { details: formdata }
      });
}

I am getting the following error:

TS2322: Type 'MutableRefObject<string>' is not assignable to type 'LegacyRef<HTMLInputElement>'.
  Type 'MutableRefObject<string>' is not assignable to type 'RefObject<HTMLInputElement>'.
    Types of property 'current' are incompatible.
      Type 'string' is not assignable to type 'HTMLInputElement'.

At reference(ref={firstName})

What did I do wrong here? I have just initialized the state variable statically instead of null, it should work fine right? Could anyone help me point out where am I missing, I have tried multiple ways of using this reference but in vain.

Edit: CodeSandbox link: https://codesandbox.io/s/cool-cache-hzu6r?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When you assign a ref to the ref property of a component it will become a ref to that component when it mounts.

In your case it will become a ref to the HTMLInputElement. So typescript expects a ref with type React.LegacyRef to be assigned to the ref property of the input element.

React.useRef(null) returns a ref with the type React.MutableRefObject which can be assigned to React.LegacyRef, because any can be assigned to HTMLInputElement or anything else.

React.useRef(SomeObject.name) returns React.MutableRefObject (because SomeObject.name is a string) and can not be assigned to React.LegacyRef because string is not a HTMLInputElement.

What you doing wrong here depends on what you a trying to do.

If you want to have a reference to an element you assign a result of React.useRef() to the ref property of the component that renders the element.

If you want to pass a ref to a component as prop you do it with some different property eg. someRef.

If you want to have a state variable you use state and not refs.

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