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

197
Visualizações
Index of first child on a list is lost when sending it to the parent with React.CloneElement (React + Typescript)

I'm building a custom Dropdown component and I'm having trouble using children.

The Dropdown component has 3 levels, and the children are the options which are passed from the grandparent Dropdown component to the grandchild Option component like so:

// GRANDPARENT
const sampleOptions = [{value: 'Option 1'}, {value: 'Option 2'}, {value: 'Option 3'}]

return (
  <Dropdown>
    {sampleOptions.map((option) => (
      <Option key={value}>{value}</Option>
    ))}
  </Dropdown>
)

The Option component is as follows:

// CHILD
const handleSelect = () => {
  onSelect && optionIndex && onSelect(optionIndex);
  // console.log(optionIndex) returns the correct index
}

return (
  <Option onClick={handleSelect} selected={selected}>
    // content
  </Option>
)

The problem occurs in the middle parent component called OptionGroup, where the index of the first child is not passed to the parent at all:

// PARENT
const [activeIndex, setActiveIndex] = useState(defaultOption)
  
const options = React.Children.map(children, (child, index) => {
  return React.cloneElement(child, {
    onSelect: (i) => {
      // console.log(i) does not work on the first child only!
      const newIndex = Number(i)
      setActiveIndex(newIndex)
    },
    selected: index === activeIndex,
    optionIndex: index,
  })
})

return (
  <OptionGroup>
    {options}
  </OptionGroup>
)

Is there something I'm missing? Thank you in advance!

about 4 years ago · Juan Pablo Isaza
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