Search code examples
javascriptformsfieldredux-form

Dynamically get fields for redux form


I'm using Redux Form with React but the form fields need to be hard coded. Is there any way to pass in the fields dynamically from the parent component?

/* form.jsx */

import React, { PropTypes } from 'react';
import { Field, reduxForm } from 'redux-form';

export const formFields = [
  'firstname',
  'lastname',
  'password'
]

class RegForm extends Component {
...
}

export default reduxForm({
    form: 'userForm',
    fields: formFields
})(RegForm);

Here is the parent component that use the redux form.

/* parent.jsx */
import RegForm from './RegForm';

...
<RegForm dynamicFields={some-dynamic-fields}>
...

If the redux form use the hard coded fields (formFields), works fine. but if I change it to,

export default reduxForm({
    form: 'userForm',
    fields: this.props.dynamicFields
})(RegForm);

It will not work, and says "cannot read from undefined..."

Any ideas on how to pass in dynamic fields to redux form?

Thanks in advance.


Solution

  • I figured it out. The dynamic fields will be passed in and received in the actual form component itself. In this case, class RegForm. In it, this.props.fields is the fields passed in from its parent component.