Search code examples
reactjsredux-form

Render fields for Redux Form from values in an array


I'm creating a filter for a graph which contains several fields. Most of them are known fields, but one part is dynamically and that is which of the houses the user want to be included in the graph. The houses are contained in my state and is different for each user (basically, the user chooses what they are named). It's the houses part here I want to render dynamically based on the props.

The only example of this that I've found is this, but I haven't found a solution on how I can transition that to my problem. I thought I could just do something like this where every house field is placed in a array (like in that example):

  renderHouseFields() {
    const { fields: { houseArray } } = this.props;
    return this.props.houses.map((house) => {
      const houseField = (
        <label
          {...houseArray}
          className="col-xs-9 control-label"
          htmlFor="cottageCheckbox"
        >
          <input type="checkbox" />
        </label>
      );

      houseArray.addField(houseField);

      return (
        <div key={house.name}>
          <label
            className="col-xs-3 control-label"
            htmlFor="cottage"
          >
            {house.name}
          </label>
          {houseField}
        </div>
      );
    });
  }

but then I simply get this error message:

Warning: setState(...): Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

This is my first project in React so I'm quite sure I'm just overlooking something here, but I can't find the solution and would be grateful if someone could help me here.

(I'm also aware that I can upgrade to redux form 6 and use FieldArray, but I don't really want to do that in the middle of the project.)


Solution

  • Judging by your code I reckon you're getting the error, because you are adding to your houseArray directly in the render method. This will trigger an update to the props of your component, which should not occur in the render method, hence the error.

    If you look at the Deep Form link you supplied, you'll notice that the only place modifications to fields are occurring, is within button event handlers.

    In your case I think what you want to do is link the entries in your house array, to the actual checkboxes. Right now you're only adding the checkboxes, but it has no reference to a house field:

    <input type="checkbox" name={house} />
    

    Or maybe this, depending on the properties of house:

    <input type="checkbox" name={`${house}.id`} />
    

    On a side note, I really would recommend to upgrade to version 6, since the API makes a lot more sense and it contains a lot of improvements over the previous version. There's a migration guide: http://redux-form.com/6.6.1/docs/MigrationGuide.md/