I have a function that looks at the provided children and if a particular element type is found, it adds some properties to it automatically.
The function is called like
The problem is a couple of things. I started by changing children: Array
to children: React.ReactNode
. You already have a check in there to narrow the type from ReactNode to ReactElement. The trick was 1. using the generic type arguments in isValidElement
and 2. using a new variable with a type assignment on it elementType
rather than dealing with and mutating the child
argument. EnrichedChildren
may need to be updated to match your use case.
interface EnrichedChildren {
onChange(): void
selectedValue: string
name: string
children?: React.ReactNode
}
enrichRadioElements = (children: React.ReactNode, name: string): any =>
React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child
}
let elementChild: React.ReactElement = child
if (child.props.children) {
elementChild = React.cloneElement(elementChild, {
children: this.enrichRadioElements(elementChild.props.children, name),
})
}
if (elementChild.type === 'Radio') {
return React.cloneElement(elementChild, {
onChange: () => {},
selectedValue: 'value',
name: name,
})
} else {
return elementChild
}
})