Reputation: 13
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>
)
}
Upvotes: 1
Views: 6744
Reputation: 18556
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>
Upvotes: 2