1

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

1 Answer 1

2

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>

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

1 Comment

don't forget to add a key prop :)

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.