Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React props.children is not array

According to the react docs, if a component has multiple 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>         );     }  }; 

Which I pass children to in another component's 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 get it to be one?

like image 610
Sebastian Sandqvist Avatar asked Sep 19 '15 20:09

Sebastian Sandqvist


People also ask

Is children prop an array?

children will be a string and not an array. So now, React. Children. map will work even if there is a single element in props.

What is a child component in React?

A Function as child component is a pattern that lets you pass a render function to a component as the children prop so you can change what you can pass as children to a component.

What is PureComponent in React?

A React component is considered pure if it renders the same output for the same state and props. For this type of class component, React provides the PureComponent base class. Class components that extend the React. PureComponent class are treated as pure components.


2 Answers

Found a better solution to this after some digging in the React.Children source. It looks like a .toArray() method has been added in React 0.14, soon to be released.

Once it is out we will be able to simply do something like this:

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

It's documented in https://reactjs.org/docs/react-api.html#reactchildren

like image 133
Sebastian Sandqvist Avatar answered Sep 23 '22 14:09

Sebastian Sandqvist


I found this solution. It will render all 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> 
like image 21
The Fool Avatar answered Sep 21 '22 14:09

The Fool