1
votes

I'm fairly new to React and I'm creating a simple toolset of form fields which use react-bootstrap. I am using a <Form> component to wrap everything in. The <Form> component will render all the child children, passing a new property.

React.Children.map(this.props.children, (child) => {
    return React.cloneElement(child, {
        myNewProp: 'hello'
    }
});

The problem I have is that the elements which are children which don't have a prop of myNewProp results in a warning Unknown props myNewProp, native HTML and react-bootstrap components. Is there any way to conditionally add props to the child element based upon the type of the component? E.g.

if (child instanceof <nativeHTMLelement>) { ... } else { ... }
2

2 Answers

1
votes

You could use child.type in this case:

if (typeof child.type === 'string') {
  // this is a html element
} else {
  // this is a React component
}
0
votes

Assuming you have isNumber and isString:

React.Children.map(this.props.children, (child) => {
    if(!child)
        return child;
    if(isNumber(child))
        return child;
    if(isString(child))
        return child;
    // then this must be a ReactElement
    if(child.type === MyElement)
        return React.cloneElement(child, {
            myNewProp: 'hello'
        }
});

If you're using typescript, isNumber and isString should be provided by @types/node. If you are not they are easy enough to implement.