Gabriel Slomka
Gabriel Slomka

Reputation: 1527

React Rendering Dynamic Inner Components

This example illustrates what i`m tryng to do.

The goal is to have a dynamic component array and render it o the screen. I`m not being able to do the rendering part.

import PropTypes from 'prop-types';
import React from 'react';
import MyComponent1 from './MyComponent1.jsx'
import MyComponent2 from './MyComponent2.jsx'

export default class KneatModalContent extends React.Component {

constructor() {
   super();
   this.components = [MyComponent1, MyComponent2];
}

render() {
  return (
  <div className='modal-contents'>
     {this.components.map(function (component, i) {
        return <{ component } key= { i } />
     })}
  </div>
)
}
}

I have tryed to create the array as [<MyComponent1/>, <MyComponent2/>] as well, as tryed to render as React.createElement(component, {key:i}) but still couldnt find a solution =(

Upvotes: 0

Views: 267

Answers (2)

Abdullah Danyal
Abdullah Danyal

Reputation: 1146

There is a problem in this line:

return <{ component } key= { i } />

Component is an instance and this is JSX, when you put component in {} braces, it means you are taking it as a JavaScript variable. Write this line as:

return <Component key={i} />

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281626

In order to create dynamic component, you could just do the following

constructor() {
   super();
   this.components = [MyComponent1, MyComponent2];
}



render() {
      return (
      <div className='modal-contents'>
         {this.components.map(function (Component, i) {
            return <Component key= { i } />
         })}
      </div>
    )
  }

Upvotes: 3

Related Questions