question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Form nested and array values mapPropsToFields not working

See original GitHub issue

Version

2.12.6

Environment

Chrome 60.0.3112.90 OSX (irrelevant in this case)

Reproduction link

https://codepen.io/MathiasGilson/pen/jLapPz

Steps to reproduce

Try to use mapPropsToFields with an array ([{ first: {value: "nameArray"} }]) or a composed object ({ first: {value: "nestedName"}}) like in the codepen

What is expected?

This should set the corresponding inputs with the given values getFieldDecorator(‘names[0].first’) input should be set to “nameArray” getFieldDecorator(‘name.first’) input should be set to “nestedName”

What is actually happening?

the input stay empty, no error in the console to debug

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:3
  • Comments:15 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
benjycuicommented, Aug 18, 2017

It’s a known issue, I don’t have enough time to dig into it. Need time to re-design data structure and behavior of nested fields.

Sorry about that.

2reactions
zcmgyucommented, Mar 5, 2019

Here is my solution

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Input } from "antd";
import merge from "lodash/merge";
import isArray from "lodash/isArray";

const transform = obj => {
  return Object.keys(obj).reduce((acc, cv) => {
    return {
      ...acc,
      [cv]:
        typeof obj[cv] === "object" && !("value" in obj[cv])
          ? isArray(obj[cv])
            ? obj[cv].map(item => transform(item))
            : transform(obj[cv])
          : Form.createFormField({
              ...obj[cv],
              value: obj[cv].value
            })
    };
  }, {});
};

const CustomizedForm = Form.create({
  name: "global_state",
  onFieldsChange(props, changedFields) {
    props.onChange(changedFields);
  },
  mapPropsToFields(props) {
    const { user } = props;
    const transformed = transform({ user });
    return transformed;
  },
  onValuesChange(_, values) {
    console.log(values);
  }
})(props => {
  const { getFieldDecorator } = props.form;
  return (
    <Form layout="inline">
      <Form.Item label="Username">
        {getFieldDecorator("user.username", {})(<Input />)}
        {getFieldDecorator("user.password", {})(<Input />)}
        {getFieldDecorator("user.children[0].name", {})(<Input />)}
        {getFieldDecorator("user.children[1].name", {})(<Input />)}
      </Form.Item>
    </Form>
  );
});

class Demo extends React.Component {
  state = {
    fields: {
      user: {
        username: {
          value: "username"
        },
        password: {
          value: "password"
        },
        children: [
          {
            name: {
              value: "name1"
            }
          },
          {
            name: { value: "name2" }
          }
        ]
      }
    }
  };

  handleFormChange = changedFields => {
    this.setState(({ fields }) => {
      return {
        fields: merge(fields, changedFields)
      };
    });
  };

  render() {
    const fields = this.state.fields;
    return (
      <div>
        <CustomizedForm {...fields} onChange={this.handleFormChange} />
        <pre className="language-bash">{JSON.stringify(fields, null, 2)}</pre>
      </div>
    );
  }
}

ReactDOM.render(<Demo />, document.getElementById("container"));

https://codesandbox.io/s/2z2ojxy22r?fontsize=14

Read more comments on GitHub >

github_iconTop Results From Across the Web

Angular nested form array mapping issue - Stack Overflow
I'm using angular reactive forms which were ok until I stared nesting form arrays. TS file: public questionForm: FormGroup; get answers(): ...
Read more >
Nested Dynamic Forms Antd - ADocLib
Within my form data model I have an array of arrays with a format be the name when the second level is also...
Read more >
Nested fields - Mantine
Manage nested arrays and object state with use-form hook. ... Set value of `name` field that is contained in object at second position...
Read more >
Bountysource
Form nested and array values mapPropsToFields not working.
Read more >
useFieldArray - Simple React forms validation
Important: update data is required and not partial. replace, (obj: object[]) => void, Replace the entire field array values.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found