SergB SergB - 2 months ago 14
React JSX Question

ReactJs: render a collection of dynamic components

I'm rather new to react.js and I wonder if it's possible to render a collection of different components with React?
For example I have a ContainerComponent class with a property childComponents which I want to use like this:

var childComponents = [];

childComponents.push(<TextComponent text={this.props.text} />);
childComponents.push(<PictureComponent src={this.props.image} />);

return (
<ContainerComponent
title={this.props.title}
innerComponents={childComponents} />
)


So the problem is that I can't call child components' render function in loop to generate single output of all children. How could render method of ContainerComponent look like?

Thanks!

Answer

Place all the components like you would normally do:

render() {
  return (
    <div>
      {this.props.innerComponents}
    </div>
  );
}

Normally, the following code should work fine for your needs:

<ContainerComponent
   title={this.props.title}
>
  <TextComponent text={this.props.text} />
  <PictureComponent text={this.props.image} />
</ContainerComponent>
Comments