Andrey Soloviev Andrey Soloviev - 19 days ago 5
React JSX Question

How render react components from array

I have several components.

formFields/index.js

export {default as description} from './description/description.component'
export {default as title} from './title/title.component'


I import them and get a list of FormFields in mainComponent

import * as FormFields from '../formFields'


How can I use them in render function?

This is one of my failed attempts:

import * as FormFields from '../formFields'

render() {

let properties = ['description', 'title'];

let getComponent = (type) => {
let formElement = FormFields[type]
return <formElement/>
}

return (
<div>
{properties.map((property, i) => {
return (
<div key={i}>
{getComponent(property)}
</div>
);
})}
</div>
)
}


This experiment is successful:

render() {
let EditComponent = FormFields['description']
return (
<div>
<EditComponent/>
</div>
)
}

Answer

Here's a simple example that also passes the same props. It is essentially an array of components that you map and then, simply render.

class Description extends React.Component {
  render() {
    return <div>{this.props.prop}</div>;
  }
}

class Title extends React.Component {
  render() {
    return <div>{this.props.prop}</div>;
  }
}

const myComponents = [
  Description,
  Title,
];

class App extends React.Component {
  render() {
    return (
      <div>
        {myComponents.map((FormField, i) => <FormField key={i} prop="Hello World!" /> )}
      </div>
    );
  }
}


ReactDOM.render(<App/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>