React & Typescript: Using React.Children.toArray()
with React.cloneElement()
Trying to clone props children when using React with Typescript, you may run into the following type error: Type 'string' is not assignable to type ReactElement...
.
React.Children.toArray(props.children)
.map(child => React.cloneElement(child));
The problem is that ReactChild
includes string | number
, which is not a valid clone target.
To solve the issue, add a type guard that checks whether the child is a valid element to clone, passing non-cloneable children through as-is:
React.Children.toArray(props.children)
.map(child => React.isValidElement(child) ? React.cloneElement(child) : child);