React props.children is not an array

According to edit documents , if a component has several children, this.props.children should be an array.

I have the following component:

export class Two extends React.Component { componentDidMount() { console.log(Array.isArray(this.props.children)); // false } render() { return( <div> {this.props.children} </div> ); } }; 

What I pass to children in another component render () method:

 <Two> <Img src="/photos/tomato.jpg"/> <Img src="/photos/tomato.jpg"/> </Two> 

Why is this.props.children not an array? More importantly, how can I make him be alone?

+12
source share
4 answers

Found the best solution for this after some jerk in the React.Children source. It seems that the .toArray() method .toArray() been added in React 0.14, which will be released soon.

Once it disappears, we can just do something like this:

 let children = React.Children.toArray(this.props.children); 
+22
source

I found this solution. This will make all the children, one or more.

 const BigMama = ({ children, styles, className }) => { return ( <div styles={{styles}} className={(className ? className : '')} > { React.Children.map(children, (child) => <React.Fragment>{child}</React.Fragment>) } </div>) } <BigMama styles={{border: 'solid groove'}} className='bass-player' > <h1>Foo</h1> <h2>Bar</h2> <h3>Baz</h3> <h4>Impossibru!</h4> <BigMama> 
+1
source

There are many ways, and some of them are already mentioned above, but if you want to make it simple and want to achieve this without any utility, then below should work

 const content = [ <Img src="/photos/tomato.jpg"/>, <Img src="/photos/tomato.jpg"/> ]; <Two> {content} </Two> 
0
source

In this case, you might find the distribution syntax useful. Have you tried this?

 <div> { [...this.props.children] } </div> 

Combine with a card to control the output.

 <div> { [...this.props.children].map(obj => <div style="someStyling"> {obj} </div> ) } </div> 
0
source

All Articles