5

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>

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't help, as the components are not of the same type. The render function doesn't know anything about the array, just that it's an array of react components.
Have you seen the fiddle? All components are different in the array. Where are you getting an array from? How the array is being passed?
Oh, my apologies... I misread the code and didn't realize at first that MyComponent was the variable from the map() function. This works like a charm, thank you!
Yeah, It seems bit misleading because normally variables are named in camelCase letters but here I was also rendering it as an element <MyComponent /> so decided not to use camelCase.
2

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

render(){
      return this.state.myArray
    }

Comments

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

1 Comment

This won't work for OPs case. It will only work when array contains react element.
-2

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})
    })
  </>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.