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?
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.
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.
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.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With