react-hero icon indicating copy to clipboard operation
react-hero copied to clipboard

Nested Fields functionality

Open jwmann opened this issue 6 years ago • 2 comments

Is there a way to use nested fields? An example would be an array of fields that nests under a common key.

import React, { Component } from 'react';
import { Input, Button } from 'antd';
import { Form, FormStore } from '@react-hero/form'

export default class MyComponent extends Component {
  constructor( props ) {
    super( props );
    this.store = new FormStore();
    this.store.set( 'filters', [{ name: undefined }], false );
  }

  render() {
    const { filters = [] } = this.store.get();
    console.log( this.store.get() );
    const fields = filters.map((_, index ) => (
      <Form.Field key={`filter-${index}`} label="Name" name={`filters[${index}]name`}>
        <Input />
      </Form.Field>
    ));
    return (
      <Form store={this.store}>
        {fields}
        <Button onClick={() => console.log( this.store.get() )}>Log FormStore</Button>
      </Form>
    );
  }
}

See Example of Nested Fields in React Hero Form

In the above example, I've created an array with 1 object inside and set it to the filters key. By setting the name to use the index of the filters themselves, I could essentially link it to the correct field.

However in practise it just make a new key called "filters[0]name" which I suppose is expected. Just wondering if this Form is capable of nested fields and I'm doing it wrong or perhaps this may be a feature request.

jwmann avatar Mar 29 '19 22:03 jwmann

A temporary solution is to replace filters[${index}]name with filters.${index}.name, I'm still thinking about a better way to support dynamic fields.

If you have any ideas, feel free to join the discussion.

varHarrie avatar Mar 30 '19 09:03 varHarrie

The workaround you suggested could sorta work but not quite what I was looking for.

I think you'd need to implement a sort've getter/setter function. If we use rc-form as an example, they use these kinds of getter/setters

https://github.com/react-component/form/blob/bbc000893f6fb6bd8bd6a95fa588e3ede2eff4b3/src/createFieldsStore.js#L204

jwmann avatar Apr 02 '19 15:04 jwmann