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

111
Visualizações
How to get index of parent object when clicking on inner property?

I have this object of objects:

[
   0: {
      id: 0,
      name: 'Bob',
      children: [
        0: { id: 0, parent: 'Bob', 'name': 'Susan'},
        1: { id: 1, parent: 'Bob', 'name': 'David'},
      ]
  },
  1: {
     id: 1,
     name: 'Christine',
     children: [
        0: { id: 0, parent: 'Christine', 'name': 'Iker'},
        1: { id: 1, parent: 'Christine', 'name': 'Ray'},
        2: { id: 2, parent: 'Christine', 'name': 'Milo'},
     ]
  },
]

I have a list that renders all the children and I have an onClick on them. How can I get index of the parent's object when I click on the individual children itself? What I have below only returns the index of the child itself.

<div onClick={() => handleAddChild(id, index)}>
  <p>{child.name}</p>
</div>

Basically when I click on a child, I want to grab the index of that child's parent object in order to update the children list for that particular parent using setState(). So if I click Iker, I should get the index 1 back of Christine's object then update state using this method (but mine is dynamic): https://stackoverflow.com/a/49502115/10211209. If there another way to do this by matching the parent name property?

Thank you!

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

0

If you are looping through and rendering the parents first and then the children. You could just pass through the parent index as an additional parameter. e.g

return this.parents.map((item, parentIndex) => (
    <span className="parent" key={index}>
        {item.children.map((child, index) => {
            <div onClick={() => handleAddChild(child.id, index, parentIndex)}>
                <p>{child.name}</p>
            </div>
        })}
    </span>
));
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