Mohamed
Mohamed

Reputation: 1271

Add custom props to this.props.children in React component

I have component which accepts children. Let's say;

<Toolbar><div>C1</div><div>C2</div></Toolbar>

When I print children using {children} inside of Toolbar, I can see them. However, I need to add/manupilate some props, so I want to iterate over them (like other arrays.map). However, when I try to use children.map I get following error.

Warning: React.createElement: type is invalid -- expected a string (for built-in 
components) or a class/function (for composite components) but got: object.

How can I achive this?

Thank you!

Edit; I mean something like;

{children.map((Child,index)=> <Child {...newProps}/>)}

Upvotes: 3

Views: 2998

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281696

You would make use of React.Children.map and then React.cloneElement to return the children after adding new props

    {React.Children.map(children, child => {
                return React.cloneElement(child, {
                    ...newProps
                });
            })}

Upvotes: 10

Related Questions