gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

How to setup Dynamic Keys? #385

Open jdarling opened 7 years ago

jdarling commented 7 years ago

Version

Requested behaviour

I'm trying to figure out how I can have a flexible object type. Basically a hash of sub objects.

As an example I might have something like:

{
  routes: {
    '/foo': {
      method: 'GET'
      ...
    },
    '/bar': {
      method: 'GET'
    }
  }
}

My first thought was to convert each to a list and then have the list maintain the key, then on submit validate that there are no duplicate keys, reform to the expected output, and return. But that seems dirty.

Any ideas?

jdarling commented 7 years ago

Seems like this should be done with dict, but that doesn't work :(

import TForm from 'tcomb-form';
const FormRender = TForm.form.Form;

const Phone = TForm.dict(
  TForm.String,
  TForm.Number
);

const Person = TForm.struct({
  firstName: TForm.String,
  lastName: TForm.String,
  phones: Phone
});

const App = React.createClass({
  onSubmit(evt) {
    evt.preventDefault()
    const value = this.refs.form.getValue()
    if (value) {
      console.log(value)
    }
  },

  render() {
    return (
      <form onSubmit={this.onSubmit}>
        <FormRender type={Person} />
        <div className="form-group">
          <button type="submit" className="btn btn-primary">Save</button>
        </div>
      </form>
    )
  }
});

That fails with the error:

Uncaught TypeError: [tcomb] [tcomb-form] unsupported kind dict for type {[key: String]: Number}