travelboy
travelboy

Reputation: 2697

Render React components from array

I have an array of references to react components. How do I render them?

myArray = [Component1, Component2, Component3];

I'm looking for the render function that, when given the array, would render this:

<div>
  <Component1 />
  <Component2 />
  <Component3 />
</div>

Upvotes: 5

Views: 4040

Answers (4)

Vitalii Andrusishyn
Vitalii Andrusishyn

Reputation: 4162

If i right understood the problem - Try set component to some variables before return into the render methods, and then into div, call this variables like object:

render:
myArray = [Component1, Component2, Component3];
var myComp1 = myArray[0];
var myComp2 = myArray[1];
var myComp3 = myArray[2];
.....some code
return
....some code
<div>
  {myComp1}
  {myComp2}
  {myComp3}
</div>

Update React 16 : (in this way no excess DIV wrapper in DOM all elements like siblings on one level)

render(): {
  const myArray = [Component1, Component2, Component3];
  .....some code
  return
  ....some code
  <>
    myArray.map((component) => {
      return({component})
    })
  </>
}

Upvotes: -2

Ankit
Ankit

Reputation: 990

In react 16 > , You can just return an array of components inside render like this:-

render(){
      return this.state.myArray
    }

Upvotes: 2

Hardik Modha
Hardik Modha

Reputation: 12736

You can iterate through each of the element of the array, where each element is the component and render it as a JSX element.

Like this, e.g. If myComponents contains [MyComponent1, MyComponent2, MyComponent3] then

renderMyComponents(myComponents){
     return myComponents.map((MyComponent, index) => {
          return (
               <li key={index}>
                   <MyComponent />
               </li>
          )
     });
}

Here is the link to JSFiddle.

Upvotes: 4

Joe
Joe

Reputation: 111

render() {
  return (
    <div>
      <ul>
        {myArray}
      </ul>
    </div>
  );
}

Upvotes: 0

Related Questions