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

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