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 =(

Answers:

Answer

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.