2
votes

Is there any way to have a dynamic form name for redux-form?

reduxForm({
  form: `${dynamicFormNameHere}`,
})(Component)

Note: Container = Smart Component, Component = Dumb Component

Currently I have a container (e.g. FilterContainer) that wrap a component with fields, and I use that container in several components. Examples:

// UserComponent.jsx
...
render() {
  ...
  <FilterContainer dynamicName="UserFilterForm" { ... } />
}

// ProductComponent.jsx
...
render() {
  ...
  <FilterContainer dynamicName="ProductFilterForm" { ... } />
}

and inside FilterContainer

mapStateToProps() { ... }
mapDispatchToProps() { ... }

let FilterContainer = connect(
  mapStateToProps,
  mapDispatchToProps,
)(reduxForm({
  form: `${dynamicName from props}`
}}(FilterComponent))

That dynamicName from props is what I wanted to achieve.

1

1 Answers

3
votes

In order to achieve this you will need to introduce a new component that wraps the reduxForm Higher-Order Component (HOC). Something like:

class DynamicFilterComponent extends React.Component {
  componentWillMount() {
    this.Filter = reduxForm({
      form: this.props.dynamicName
    })(FilterComponent)
  }

  render() {
    const Filter = this.Filter
    return <Filter {...this.props} />
  }
}

Then wrap this in connect:

mapStateToProps() { ... }
mapDispatchToProps() { ... }

let FilterContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(DynamicFilterComponent)

Note: When dealing with HOCs you must be careful when creating them dynamically. I created the reduxForm HOC in componentWillMount so that it is the same instance used for each render call. This is important for React's diffing algorithm.