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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source