Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass props to children with React.cloneElement?

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
like image 892
imrok Avatar asked Oct 18 '22 05:10

imrok


1 Answers

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!

like image 103
Tharaka Wijebandara Avatar answered Oct 20 '22 23:10

Tharaka Wijebandara