k88hudson / react-formation

Robust, testable forms with react in minutes
https://k88hudson.github.io/react-formation
33 stars 9 forks source link

Using props as initial values #21

Closed eiriklv closed 8 years ago

eiriklv commented 9 years ago

What about passing props to react-formation forms to be used as initial values?

Since the schema is a static on the object you pass to CreateForm I mean..

I'm not sure what the best kind of api for this would be, but what I would want is something that enables me to do this in some sort of way (without any hacks):

NoteForm

const NoteForm = CreateForm({
  schema: {
    subject: {
      label: 'Subject',
      type: isMinLength(20),
      required: true
    },
    content: {
      label: 'Content',
      type: isMinLength(40),
      required: true,
    }
  },

  onSuccess(data) {
    const { handleSuccess } = this.props;
    handleSuccess(data);
  },

  render() {
    return (
      <form>
        <div className="form-group">
          <label>Name (error is shown after submit attempt)</label>
          <input
            type="text"
            name="subject"
            valueLink={this.linkField('subject')}
          />
          <ErrorMessage field="subject" />
        </div>

        <div className="form-group">
          <label>Email (error is shown immediately)</label>
          <input 
            type="text"
            name="content"
            valueLink={this.linkField('content')}
          />
          <ErrorMessage show={true} field="content" />
        </div>

        <p><button onClick={this.submitForm}>Submit</button></p>
    </form>
    );
  }
});

Component using NoteForm:

export default class Note extends Component {
  .....

  render() {
    const { note } = this.props;

    return (
      <div>
        <NoteForm
          initial={note}
          handleSuccess={this.handleSuccess}
        />
      </div>
    );
  }
}

Changes in CreateForm.js to make this work (hacky..):

config.mixins.push({
    getInitialState: function getInitialState() {
      var _this = this;

      var state = {
        didSubmit: false,
        dirtyFields: {}
      };

      Object.keys(this.schema).forEach(function (key) {
        state.dirtyFields[key] = false;
        state[key] = _this.props.initial[key]; // new way to be able to use props as initial values
        //state[key] = schema[key].initial; // old way
      });

      return state;
    },

What are your thoughts about this..? Should schema be a function getSchema instead, that enables you to use props?

eiriklv commented 9 years ago

Love the project btw - Great work! :-)

k88hudson commented 9 years ago

Ha, you read my mind! I think getSchema seems like a good idea.

k88hudson commented 8 years ago

Thanks for adding this! :+1:

eiriklv commented 8 years ago

Np :)