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

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

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