An extension to the great formik-library.
The main goal is to keep the simplicity of formik's <Field>
-component and to remove the magic introduced by the implicit context and the name-string. In addition, when updating one field, you do not want to have to render all the others again.
FormikFields is available as an npm-package and has formik as peer-dependency:
yarn add formik formik-fields
# or npm
npm install formik formik-fields
import * as React from 'react';
import { FormikFields } from 'formik-fields';
import { FormikFieldInput } from './your-custom-component';
interface MyFormValues {
email: string;
name: string;
}
export const MyForm = () => (
<FormikFields<MyFormValues>
fields={{
name: {
initialValue: '',
validate: val => !val && 'Name should not be empty'
},
email: { initialValue: '' }
}}
onSubmit={(values: MyFormValues) => console.log(values)}
render={(fields, formikBag) => (
<form onSubmit={formikBag.handleSubmit}>
<FormikFieldInput field={fields.email} />
<FormikFieldInput field={fields.name} />
<button type="submit">submit</button>
</form>
)}
/>
);
The <FormikFields>
-Component accepts following props:
Type:
{ [fieldName]: FieldDefinition }
const formikFieldDefinition = {
name: {
initialValue: '',
validate: val => !val && 'Name should not be empty'
},
email: { initialValue: '' }
};
Name | Type | Description |
---|---|---|
initialValue (required) | Value |
Initial value when the form is first mounted. |
validate | (val: Value) => any |
If not falsy, the fields error -prop is set with the computed value from this function. See formik's How Form Submission Works to understand how validation works. |
type:
(fieldsState, formikProps) => ReactNode
You can also use the children
-prop, for more usage about the render-prop-pattern head over the the react-documentation.
type :
{ [fieldName]: FieldState }
FieldState
is an Object
with following members:
Name | Type | Description |
---|---|---|
name |
string |
equal to the corresponding key in the fieldsState -Object |
value |
FormValue[name] |
current value, on mount equal to initialValue in the FieldDefinition |
isTouched |
boolean (default: false ) |
result from setIsTouched or handleBlur |
error |
any |
result from the validate -function in the FieldDefinition |
setValue |
(val: FormValue[name], shouldValidate = true) => void |
set value and re-evaluate your validators, calls internally formik's setFieldValue |
setIsTouched |
(isTouched: boolean, shouldValidate = true) => void |
set isTouched and re-evaluate your validators, calls internally formik's setFieldTouched |
handleChange |
(e: React.ChangeEvent) => void |
calls setValue with the extracted value from an input-onChange -callback |
handleBlur |
() => void |
calls setIsTouched(true) |
The second callback-parameter contains all props from Formik's render-prop-callback, visit their documentation for more information.
This project is written in TypeScript and so typings should always be up-to-date. You should always enhance the <FormikFields>
-Component with your form-values-Interface (since TypeScript 2.9 you can do this inline):
interface MyFormValues {
email: string;
name: string;
}
export const MyForm = () => <FormikFields<MyFormValues> {/*...*/} />
Now your fields and render-prop-parameters are enhanced with your specific field-names and -types.
You can use FormikFields as well as formik without TypeScript (via ES6-import
or require
). However, you lose the advantages of the types in your forms (with TS the fields are checked against the initial definitions of the form-values-structure and so you can only access defined fields).
A minimum implementation of a FormikFieldInput
in TypeScript could look like this:
import { PureComponent } from 'react';
import { FormikFieldState } from 'formik-fields';
interface FormikFieldInputProps {
field: FormikFieldState<string>;
}
// Use React.PureComponent component to take advantage of the optimized fields
export class FormikFieldInput extends PureComponent<FormikFieldInputProps> {
render() {
const { field, ...props } = this.props;
return (
<div>
<input
onChange={field.handleChange}
onBlur={field.handleBlur}
value={field.value}
{...props}
/>
{field.isTouched && field.error && <div>({field.error})</div>}
</div>
);
}
}
Since this is only an extension, <FormikFields>
accepts all props of the actual <Formik>
component (except Component
and initialValues
, which is overwritten by your field-definitions).
When you define Formik's validate
-prop, the results of the specifically defined validate
function are merged with the results of the field-validations (where the specific validate
function overwrites the values of the field-validations if they have the same keys).
If you define a field-level-validate
-function via the FieldDefinition, the result of your function can prevent your form to submit:
If this function returns a falsy value, this field will not prevent your form to submit. Otherwise, the form validation corresponds to that of Formik, see How Form Submission Works in their documentation.
for advanced validations you can use formik's
validate
-prop
your field-validator-function HAVE TO be always a pure function with only one parameter (the field-value itself). Under this assumption, the results of the validations are memoized. The fields are only renewed if there are actual changes. So you can use Reacts PureComponent to improve the performance of your forms.