Render Redux Form fields programmatically

Viewed 64

I have a question about Redux Form fields. I have just a simple form that I want to create, and it has just a firstName field and a lastName field.

Rather than writing out the code for both fields like:

<Field
  id="firstName"
  name="firstName"
  component={FormField}
  validate={this.myValidation}
  ...
/>

<Field
  id="lastName"
  name="lastName"
  component={FormField}
  validate={this.myValidation}
  ...
/>

Since they are so similar, is there a way to programmatically render these fields? I ask because there will be additional fields that are also essentially the same, and it seems like there is a better way to do so than to write them each out like the above.

Hoping my question makes sense. Just looking to keep the code as DRY as possible, and have lesser code doing more.

Thanks for any suggestions anyone might offer...

3 Answers

You could declare a field render function, for example:

...

renderField(name) {
  return (
    <Field
      id={name}
      name={name}
      component={FormField}
      validate={this.myValidation}
      ...
    />
  );
}

...

render() {
  return (
    <div>
      {this.renderField('firstName')}
      {this.renderField('lastName')}
      ...
    </div>
    ...
  );
}

...

While this is probably overkill for two fields, you can also use a map function that returns an array of React components.

render() {
    return(
        <div>
            {['firstName', 'lastName'].map((el) => {
                return(
                    <Field
                        id={el}
                        name={el}
                        component={FormField}
                        validate={this.myValidation}
                    />
                )
            })}
        </div>
}

Or, to go even further, you could combine this with Sergey Denisov's answer and pass a function to create a component into that map. e.g. ['firstName', 'lastName'].map((el) => this.renderField(el))

You're doing it the way it should be done, you're writing out what you want (declaring these two fields). I don't see any reason to abstract this out any further. I know this isn't much of an answer but sometimes not doing stuff is better than spending extra time effort for minimal gains.

Related