varHarrie / react-hero

💼 React toolkit.
http://varharrie.me/react-hero
MIT License
41 stars 5 forks source link

Nested Fields functionality #2

Open jwmann opened 5 years ago

jwmann commented 5 years ago

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.

varHarrie commented 5 years ago

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.

jwmann commented 5 years ago

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