react-generic-forms
Use typesafe forms for your react apps.
This library is heavily inspired by Formik, but from the beginning with typescript in mind.
How it works
- You have to define all the fields for your form (optional with validators) and its initial values
- The form accepts a function as child, which will pass all
fields
and anisSubmitting
property - All input components have to be connected to a specific field. They have to change the
field.value
property in itsonChange
event. - A submit button (
<input type="submit" />
) will trigger the validation and will call theonSubmit
handler only if all fields are valid. - Within the
onSubmit
handler you have access to the original reactevent
, allvalues
and to formactions
.
Example
// common.ts // probably there are some interfaces shared between client and server
// signup.ts ;; ;; // create the fields// hint: required() is needless while using any other validator; // define initial values; // implement submit handler; // implement form component;
// input.ts ;; // a custom input component which renders validation errors
Custom inputs
As the inputs only have to implement the onChange
handler you can use the native html input elements or custom ones like React Select. For this reason, there is no default input component included.
Custom validators
The following types are used to define a custom validator:
type ValidationFunction<FieldValueType = any, T = any> = (value: FieldValueType | null | undefined, fields: Fields<T>) => string | null
type CustomValidator = (...params: any[]) => ValidationFunction<T, F>
remark:
FieldValueType
is the type of the field to validateT
is the generic type of the form
So to implement your custom validator
- create a function with own validator settings
- return a function with the current value and optional all fields as parameters
- return null, if the field is valid or an error message, if it's not.
example:
// simple validator // more complex validator