5

I'm trying to pass props to my component children but I have this error : Unknown prop 'user' on tag. Remove this prop from the element.

When looking at documentation and questions, I think I understood that props given to React.cloneElement (second argument) must be DOM recognized properties.

So my question is how to pass props to the component children and make them accessible in this.props ?

Here is my code :

render() {

    const { children } = this.props
    const { user } = this.state

    const childrenWithProps = React.Children.map(children, child =>
        React.cloneElement(child, { user })    
    )

    return (
        <div>
            { childrenWithProps }
        </div>
    )
}

edit : the children component's propTypes

ChildrenPage.propTypes = {
    user: PropTypes.object
}

export default ChildrenPage
imrok
  • 787
  • 1
  • 9
  • 23

2 Answers2

3

Your code looks fine for me. Usually, React give this warning when you are trying to render DOM element(Not a React Component) with invalid/non-standard DOM attribute.

In your case, this might happen if your children collection has a DOM element. Since user is not a standard DOM attribute, it might fire this warning when you are trying to clone the element with user prop.

You can read more about this error here.

Hope this helps!

Tharaka Wijebandara
  • 7,955
  • 1
  • 28
  • 49
0

Make sure that you are not passing down the children key as props. Below code removes children key from props before passing it down to the children.

let key = 'children';
let {[key]: _, ...newProps} = state;
{React.Children.map(this.props.children, child => 
  React.cloneElement(child, {...newProps}))}

This is one of the possible reasons. and, let me know if this solution works. For more, https://facebook.github.io/react/warnings/unknown-prop.html

Charanjeet Kaur
  • 1,199
  • 3
  • 14
  • 27
  • In my code, I'm trying to pass a newly created object `{ user }` without references to the parent object. In addition, and related to the linked doc, I even tried to clone the "user" object `React.cloneElement(child, { user: Object.assign({}, user) }) ` but still have the error for the props "user" in div tag. – imrok Sep 27 '17 at 10:31
  • @OhmWang have you mentioned PropTypes for the child components? and, do they match with { user } – Charanjeet Kaur Sep 28 '17 at 12:39
  • I tried adding the propTypes on the child component but the error remains. You can see it in my initial post edit. – imrok Sep 28 '17 at 14:09
  • 1. Is it only a warning or an error? 2. Show how you use props in children page. – MistyK Sep 30 '17 at 10:18