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

140
Vistas
React refs created from Array not working

I'm trying to use refs created from an array but when I check in the Component tab of the React Developper Tools, ref passed to the input are always undefined. Something I missed here?

const MyComponent = () => {
  const refs = useMemo(() => Array(2).fill(0).map(i => React.createRef()), []);

  const TextInput = ({ name, value, inputRef }) => (
    <input
      name={name}
      value={value}
      onChange={updateField()}
      ref={inputRef}
    />
  )

  return (
    <TextInput
      name="lastname"
      value="Nom *"
      inputRef={refs[0]}
    />
    <TextInput
      name="firstname"
      label="Prénom *"
      inputRef={refs[1]}
    />
  )
}

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you have a variable number of refs, you'll want a function-style ref instead, like below.

const TextInput = ({
  name,
  value,
  refs
}) => (
  <input
    name={name}
    value={value}
    ref={(el) => {
      refs.current[name] = el;
    }}
  />
);

const MyComponent = () => {
  const refs = React.useRef({});

  React.useLayoutEffect(() => {
    console.log(refs.current);
  }, []);

  return (
    <>
      <TextInput name="lastname" value="Nom *" refs={refs} />
      <TextInput name="firstname" value="Prénom *" refs={refs} />
    </>
  );
};

This will log

{lastname: HTMLInputElement, firstname: HTMLInputElement}

As an aside: never nest components – that will cause unnecessary rerenders.

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