form-provider
A set of React helpers to help with building forms. State is managed with a Redux store that is local to your component. This promotes keeping your ui state separate from your global application state while still being able to use the redux ecosystem.
Demos:
Installation
npm install --save react react-dom redux react-redux # peer dependencies npm install --save form-provider
Basic Usage
// BasicForm.js { return field1: propsfield1 obj: field2: 4 } { return <FormProvider form=form onSubmit=onSubmit> <form onSubmit=> <h3>Basic Form</h3> <Field path='field1' validate= > <div> <label>Field1*</label> <input type='text' value=value onChange= /> error && <div> errormessage </div> </div> </Field> <Field path='obj.field2'> <div> <label>Field2</label> <input type='number' value=value onChange=) /> </div> </Field> <button type='submit'>Save</button> <button type='button' onClick=formreset>Reset</button> </form> </FormProvider> } createFormBasicForm
Check out the basic form example for the entire source.
Initial state
Setting initial form state is done by passing it into withForm
... user: firstName: 'john' BasicForm // or as a function of props user: propsuserBasicForm
Validation
This lib currently doesn't provide any validation functions out of the box, only an API to provide your own. Validators are functions that accept the current value and return a promise. Pass in a single validator or an array to the <Field>
component. The form won't submit until all validators are resolved.
// validators.js const isRequired = { if !value return } const isNotNumber = { if ! return }
Binding to form state
Use the connectForm
function to map form state to props. This function has the exact same API as react-redux's connect
function. You can use this to conditionally display fields or other rendering logic based on the current form's state.
{ return userFormState: formStateuser allErrors: formStateerrors } { ...}) withForm
Alternatives
- React Redux Form: Personal favourite, similar API.
- Redux Form: More features out of the box, mature and popular.
- React Forms: Validate with JSONSchema, no redux dependency