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

97
Visualizações
React ref is only updating one instance

Got an interesting problem withs refs.

I'm mapping over a component and rendering it multiple times and passing a ref to each one

const ref = useRef()

{data.map(d) => (
  <Component
    {...lotsOfOtherProps}
    ref={ref}
  />
)}

Then in a grandchild component I have:

  const anotherRef = React.useRef()
  useImperativeHandle(ref, () => ({
    reset: () => {
      anotherRef?.current.reset()
    },
  }))

In this component I have a button and when I toggle it I call

anotherRef?.current?.reset() and this works and does what I want

but I'm wondering when I click a "reset all" button, how I can get all the refs to reset?

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

0

You are replacing the ref with each iteration and finally assigning it to the last element. You need to create an array of refs.

const refs = [];

{
  data.map((d, index) => {
    const newRef = React.createRef();
    refs[index] = newRef;
    return <Component {...lotsOfOtherProps} ref={newRef} />;
  });
}

refs will contain the array of ref for each component created from data array.

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