score:175

Accepted answer

The problem is that the definition for ReactChild is this:

type ReactText = string | number;
type ReactChild = ReactElement<any> | ReactText;

If you're sure that child is always a ReactElement then cast it:

return React.cloneElement(child as React.ReactElement<any>, {
    width: this.props.width,
    height: this.props.height
});

Otherwise use the isValidElement type guard:

if (React.isValidElement(child)) {
    return React.cloneElement(child, {
        width: this.props.width,
        height: this.props.height
    });
}

(I haven't used it before, but according to the definition file it's there)

score:24

This solved it for me:

React.Children.map<ReactNode, ReactNode>(children, child => {
    if(React.isValidElement(child)) {
      return React.cloneElement(child, props
      )
    }
  }

quite simplle solution


Related Query

More Query from same tag