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

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

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 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