# Formik > If you would like to use Formik with a UI framework, you'll probably want to create a wrapper component that binds Formik's props and callbacks. --- # Formik Documentation # Source: https://formik.org/docs/3rd-party-bindings # Path: /docs/3rd-party-bindings #### Documentation #### API Reference #### Documentation #### API Reference # 3rd Party Bindings If you would like to use Formik with a UI framework, you'll probably want to create a wrapper component that binds Formik's props and callbacks. A few popular frameworks have open source wrappers readily available: - Ant Design - Fabric - Material UI - Reactstrap - Semantic UI 2.0 - Semantic UI #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/api/connect # Path: /docs/api/connect #### Documentation #### API Reference #### Documentation #### API Reference # connect() connect()is a higher-order component (HoC) that allows you to hook anything into Formik's context. It is used internally to constructand
, but you can use it to build out new components as your needs change. `connect()` `` `` ## Type signature ``` connect(Comp:React.ComponentType}>)=>React.ComponentType ``` ## Example ``` 1importReactfrom'react';2import{connect,getIn}from'formik';34// This component renders an error message if a field has5// an error and it's already been touched.6constErrorMessage=props=>{7// All FormikProps available on props.formik!8consterror=getIn(props.formik.errors,props.name);9consttouch=getIn(props.formik.touched,props.name);10returntouch&&error?error:null;11};1213exportdefaultconnect(ErrorMessage); ``` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/api/errormessage # Path: /docs/api/errormessage #### Documentation #### API Reference #### Documentation #### API Reference # is a component that renders the error message of a given field if that field has been visited (i.e.touched[name] === true) (and there is anerrormessage present). It expects that all error messages are stored for a given field as a string. Like,, and, lodash-like dot path and bracket syntax is supported. `` `touched[name] === true` `error` `` `` `` ## Example ``` 1import React from 'react';2import { Formik, Form, Field, ErrorMessage } from 'formik';3import * as Yup from "yup";45const SignupSchema = Yup.object().shape({6name: Yup.string()7.min(2, 'Too Short!')8.max(70, 'Too Long!')9.required('Required'),10email: Yup.string()11.email('Invalid email')12.required('Required'),13});1415export const ValidationSchemaExample = () => (16
17

Signup

18 {25// same shape as initial values26console.log(values);27}}28>29{({ errors, touched }) => (303132-{errors.name && touched.name ? (33-
{errors.name}
34-) : null}35+3637-{errors.email && touched.email ? (38-
{errors.email}
39-) : null}40+414243)}4445
46); ``` #### Props # Reference ## Props ### children `children` children?: ((message: string) => React.ReactNode) `children?: ((message: string) => React.ReactNode)` A function that returns a valid React element. Will only be called when the field has been touched and an error exists. ``` 1// the render callback will only be called when the2// field has been touched and an error exists and subsequent updates.3{msg=>
{msg}
}
``` ### component `component` component?: string | React.ComponentType `component?: string | React.ComponentType` Either a React component or the name of an HTML element to render. If not specified,will just return a string. `` ``` 12// --> {touched.email && error.email ?
{error.email}
: null}345// --> {touched.email && error.email ? {error.email} : null}678// --> {touched.email && error.email ? {error.email} : null}91011// This will return a string. React 16+.12// --> {touched.email && error.email ? error.email : null} ``` ### id `id` id?: string `id?: string` A field's id in Formik state. To get access to DOM elements for e2e testing purposes, it doesn't impact the implementation in any way as the prop can still be omitted. ``` 1// id will be used only for testing purposes2// not contributing anything to the core implementation.3 ``` ### name `name` name: stringRequired `name: string` A field's name in Formik state. To access nested objects or arrays, name can also accept lodash-like dot path likesocial.facebookorfriends[0].firstName `social.facebook` `friends[0].firstName` ### render `render` render?: (error: string) => React.ReactNode `render?: (error: string) => React.ReactNode` A function that returns a valid React element. Will only be called when the field has been touched and an error exists. ``` 1// the render callback will only be called when the2// field has been touched and an error exists and subsequent updates.3
{msg}
}/> ``` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/api/fastfield # Path: /docs/api/fastfield #### Documentation #### API Reference #### Documentation #### API Reference # ## Before we start is meant for performanceoptimization. However, you really do not need to use it until you do. Only proceed if you are familiar with how React'sshouldComponentUpdate()works. You have been warned. `` `shouldComponentUpdate()` No. Seriously. Please review the following parts of the official React documentation before continuing - ReactshouldComponentUpdate()Reference `shouldComponentUpdate()` - shouldComponentUpdatein Action `shouldComponentUpdate` ## Overview is an optimized version ofmeant to be used on large forms (~30+ fields) or when a field has very expensive validation requirements.has the same exact API as, but implementsshouldComponentUpdate()internally to block all additional re-renders unless there are direct updates to the's relevant parts/slice of Formik state. `` `` `` `` `shouldComponentUpdate()` `` For example,will only re-render when there are: `` - Changes tovalues.firstName,errors.firstName,touched.firstName, orisSubmitting. This is determined by shallow comparison. Note: dotpaths are supported. `values.firstName` `errors.firstName` `touched.firstName` `isSubmitting` - A prop is added/removed to the `` - Thenameprop changes `name` Other than for these aforementioned situations,will not re-render when other parts of Formik state change. However, all updates triggered by awill trigger re-renders to other "vanilla"components. `` `` `` ## When to use `` If ais "independent" of all other's in your form, then you can use. `` `` `` More specifically, if thedoes not change behavior or render anything that is based on updates to anotheror's slice of Formik state AND it does not rely on other parts of top-levelstate (e.g.isValidating,submitCount), then you can useas a drop-in replacement to. `` `` `` `` `isValidating` `submitCount` `` `` ## Example ``` 1importReactfrom'react';2import{Formik,Field,FastField,Form}from'formik';3import*asYupfrom'yup';45constBasic=()=>(6
7

Sign Up

8{21setTimeout(()=>{22alert(JSON.stringify(values,null,2));23},500);24}}25>26{formikProps=>(27
28{/** This only updates for changes made to29values.firstName, touched.firstName, errors.firstName */}30First Name313233{/** Updates for all changes because it's from the34top-level formikProps which get all updates */}35{formikProps.touched.firstName&&formikProps.errors.firstName&&(36
{formikProps.errors.firstName}
37)}3839Middle Initial4041{({field,form,meta})=>(42
4344{/**45* This updates normally because it's from the same slice of Formik state,46* i.e. path to the object matches the name of this 47*/}48{meta.touched?meta.error:null}4950{/** This won't ever update since it's coming from51from another /'s (i.e. firstName's) slice */}52{form.touched.firstName&&form.errors.firstName53?form.errors.firstName54:null}5556{/* This doesn't update either */}57{form.submitCount}5859{/* Imperative methods still work as expected */}6064J6566
67)}68
6970{/** Updates for all changes to Formik state71and all changes by all s and s */}72LastName7374{({field,form,meta})=>(75
7677{/** Works because this is inside78of a , which gets all updates */}79{form.touched.firstName&&form.errors.firstName80?form.errors.firstName81:null}82
83)}84
8586{/** Updates for all changes to Formik state and87all changes by all s and s */}88Email899091Submit9293)}9495
96); ``` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/api/field # Path: /docs/api/field #### Documentation #### API Reference #### Documentation #### API Reference # will automagically hook up inputs to Formik. It uses thenameattribute to match up with Formik state.will default to an HTMLelement. `` `name` `` `` ## Rendering There are a few different ways to render things with. `` - `` - `` - `` - deprecated in 2.x. Using these will log warning `` ascan either be a React component or the name of an HTML element to render. Formik will automagically injectonChange,onBlur,name, andvalueprops of the field designated by thenameprop to the (custom) component. `as` `onChange` `onBlur` `name` `value` `name` childrencan either be an array of elements (e.g.
4849); ``` #### Props # Reference ## Props ### as `as` as?: string | React.ComponentType `as?: string | React.ComponentType` Either a React component or the name of an HTML element to render. That is, one of the following: - input `input` - select `select` - textarea `textarea` - A valid HTML element name - A custom React component Custom React components will be passedonChange,onBlur,name, andvalueplus any other props passed directly to. `onChange` `onBlur` `name` `value` `` Default is'input'(so anis rendered by default) `'input'` `` ``` 1// Renders an HTML by default234// Renders an HTML is rendered by default) `'input'` `` ``` 1// Renders an HTML by default234// Renders an HTML and passes FieldProps field property2(56)}7/>89// Renders an HTML and disables it while form is submitting10(1314)}15/>1617// Renders an HTML with custom error
element18(21
2223{touched[field.name]&&24errors[field.name]&&{errors[field.name]}
}25
26)}27/> ``` ### validate `validate` validate?: (value: any) => undefined | string | Promise `validate?: (value: any) => undefined | string | Promise` You can run independent field-level validations by passing a function to thevalidateprop. The function will respect thevalidateOnBlurandvalidateOnChangeconfig/props specified in the'sparent/withFormik. This function can either be synchronous or asynchronous: `validate` `validateOnBlur` `validateOnChange` `'s` `` `withFormik` - Sync: if invalid, return astringcontaining the error message or returnundefined. Sync: if invalid, return astringcontaining the error message or returnundefined. `string` `undefined` - Async: return a Promise that resolves astringcontaining the error message. This works like Formik'svalidate, but instead of returning anerrorsobject, it's just astring. Async: return a Promise that resolves astringcontaining the error message. This works like Formik'svalidate, but instead of returning anerrorsobject, it's just astring. `string` `validate` `errors` `string` ``` 1importReactfrom'react';2import{Formik,Form,Field}from'formik';34// Synchronous validation function5constvalidate=value=>{6leterrorMessage;7if(!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)){8errorMessage='Invalid email address';9}10returnerrorMessage;11};1213// Async validation function14constsleep=ms=>newPromise(resolve=>setTimeout(resolve,ms));1516constvalidateAsync=value=>{17returnsleep(2000).then(()=>{18if(['admin','null','god'].includes(value)){19return'Nice try';20}21});22};2324// example usage25constMyForm=()=>(26alert(JSON.stringify(values,null,2))}29>30{({errors,touched})=>(31
3233{errors.email&&touched.email?
{errors.email}
:null}3435{errors.username&&touched.username?(36
{errors.username}
37):null}38Submit3940)}41
42); ``` Note: To allow for i18n libraries, the TypeScript typings forvalidateare slightly relaxed and allow you to return aFunction(e.g.i18n('invalid')). `validate` `Function` `i18n('invalid')` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/api/fieldarray # Path: /docs/api/fieldarray #### Documentation #### API Reference #### Documentation #### API Reference # is a component that helps with common array/list manipulations. You pass it anameproperty with the path to the key withinvaluesthat holds the relevant array.will then give you access to array helper methods via render props. For convenience, calling these methods will trigger validation and also managetouchedfor you. `` `name` `values` `` `touched` ``` 1importReactfrom'react';2import{Formik,Form,Field,FieldArray}from'formik';34// Here is an example of a form with an editable list.5// Next to each input are buttons for insert and remove.6// If the list is empty, there is a button to add an item.7exportconstFriendList=()=>(8
9

Friend List

1013setTimeout(()=>{14alert(JSON.stringify(values,null,2));15},500)16}17render={({values})=>(18
19(22
23{values.friends&&values.friends.length>0?(24values.friends.map((friend,index)=>(252627arrayHelpers.remove(index)}// remove a friend from the list30>31-3233arrayHelpers.insert(index,'')}// insert an empty string at a position36>37+3839
40))41):(42arrayHelpers.push('')}>43{/* show this when user has removed all friends from the list */}44Add a friend4546)}47
48Submit49
50
51)}52/>5354)}55/>5657); ``` ### name: string `name: string` The name or path to the relevant key invalues. `values` ### validateOnChange?: boolean `validateOnChange?: boolean` Default istrue. Determines if form validation should or should not be runafterany array manipulations. `true` ## FieldArray Array of Objects You can also iterate through an array of objects, by following a convention ofobject[index].propertyorobject.index.propertyfor the name attributes oforelements in. `object[index].property` `object.index.property` `` `` `` ``` 1
2(5
6{values.friends.map((friend,index)=>(78{/** both these conventions do the same */}9101112arrayHelpers.remove(index)}>13-1415
16))}17arrayHelpers.push({name:'',age:''})}20>21+222324)}25/>26 ``` ## FieldArray Validation Gotchas Validation can be tricky with. `` If you usevalidationSchemaand your form has array validation requirements (like a min length) as well as nested array field requirements, displaying errors can be tricky. Formik/Yup will show validation errors inside out. For example, `validationSchema` ``` 1constschema=Yup.object().shape({2friends:Yup.array()3.of(4Yup.object().shape({5name:Yup.string().min(4,'too short').required('Required'),// these constraints take precedence6salary:Yup.string().min(3,'cmon').required('Required'),// these constraints take precedence7})8)9.required('Must have friends')// these constraints are shown if and only if inner constraints are satisfied10.min(3,'Minimum of 3 friends'),11}); ``` Since Yup and your custom validation function should always output error messages as strings, you'll need to sniff whether your nested error is an array or a string when you go to display it. So...to display'Must have friends'and'Minimum of 3 friends'(our example's array validation constraints)... `'Must have friends'` `'Minimum of 3 friends'` Bad ``` 1// within a `FieldArray`'s render2constFriendArrayErrors=errors=>3errors.friends?
{errors.friends}
:null;// app will crash ``` Good ``` 1// within a `FieldArray`'s render2constFriendArrayErrors=errors=>3typeoferrors.friends==='string'?
{errors.friends}
:null; ``` For the nested field errors, you should assume that no part of the object is defined unless you've checked for it. Thus, you may want to do yourself a favor and make a customcomponent that looks like this: `` ``` 1import{Field,getIn}from'formik';23constErrorMessage=({name})=>(4{7consterror=getIn(form.errors,name);8consttouch=getIn(form.touched,name);9returntouch&&error?error:null;10}}11/>12);1314// Usage15;// => null, 'too short', or 'required' ``` NOTE: In Formik v0.12 / 1.0, a newmetaprop may be added toFieldandFieldArraythat will give you relevant metadata such aserror&touch, which will save you from having to use Formik or lodash's getIn or checking if the path is defined on your own. `meta` `Field` `FieldArray` `error` `touch` ## FieldArray Helpers The following methods are made available via render props. - push: (obj: any) => void: Add a value to the end of an array `push: (obj: any) => void` - swap: (indexA: number, indexB: number) => void: Swap two values in an array `swap: (indexA: number, indexB: number) => void` - move: (from: number, to: number) => void: Move an element in an array to another index `move: (from: number, to: number) => void` - insert: (index: number, value: any) => void: Insert an element at a given index into the array `insert: (index: number, value: any) => void` - unshift: (value: any) => number: Add an element to the beginning of an array and return its length `unshift: (value: any) => number` - remove(index: number): T | undefined: Remove an element at an index of an array and return it `remove(index: number): T | undefined` - pop(): T | undefined: Remove and return value from the end of the array `pop(): T | undefined` - replace: (index: number, value: any) => void: Replace a value at the given index into the array `replace: (index: number, value: any) => void` ## FieldArray render methods There are three ways to render things with `` - `` - `` - `` ### render: (arrayHelpers: ArrayHelpers) => React.ReactNode `render: (arrayHelpers: ArrayHelpers) => React.ReactNode` ``` 1importReactfrom'react';2import{Formik,Form,Field,FieldArray}from'formik'34exportconstFriendList=()=>(5
6

Friend List

7(11(14
15{/*... use these however you want */}16
17)}18/>19/>20
21); ``` ### component: React.ReactNode `component: React.ReactNode` ``` 1importReactfrom'react';2import{Formik,Form,Field,FieldArray}from'formik'345exportconstFriendList=()=>(6
7

Friend List

8(1216)}17/>18
19);202122// In addition to the array helpers, Formik state and helpers23// (values, touched, setXXX, etc) are provided through a `form`24// prop25exportconstMyDynamicForm=({26move,swap,push,insert,unshift,pop,form27})=>(28
29{/** whatever you need to do */}30
31); ``` ### children: func `children: func` ``` 1importReactfrom'react';2import{Formik,Form,Field,FieldArray}from'formik'345exportconstFriendList=()=>(6
7

Friend List

8(1213{({move,swap,push,insert,unshift,pop,form})=>{14return(15
16{/*... use these however you want */}17
18);19}}2021)}22/>23
24); ``` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/api/form # Path: /docs/api/form #### Documentation #### API Reference #### Documentation #### API Reference #
Form is a small wrapper around an HTMLelement that automatically hooks into Formik'shandleSubmitandhandleReset. All other props are passed directly through to the DOM node. `` `handleSubmit` `handleReset` ``` 1// so...234// is identical to this...5 ``` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/api/formik # Path: /docs/api/formik #### Documentation #### API Reference #### Documentation #### API Reference # is a component that helps you with building forms. It uses a render props pattern made popular by libraries like React Motion and React Router. `` ## Example ``` 1importReactfrom'react';2import{Formik}from'formik';34constBasicExample=()=>(5
6

My Form

7{10setTimeout(()=>{11alert(JSON.stringify(values,null,2));12actions.setSubmitting(false);13},1000);14}}15>16{props=>(171825{props.errors.name&&{props.errors.name}
}26Submit2728)}29
3031); ``` #### Props # Reference ## Props ### Formik render methods and props There are 2 ways to render things with `` - `` - `` - Deprecated in 2.x `` Each render methods will be passed the same props: #### dirty: boolean `dirty: boolean` Returnstrueif values are not deeply equal from initial values,falseotherwise.dirtyis a readonly computed property and should not be mutated directly. `true` `false` `dirty` #### errors: { [field: string]: string } `errors: { [field: string]: string }` Form validation errors. Should match the shape of your form'svaluesdefined ininitialValues. If you are usingvalidationSchema(which you should be), keys and shape will match your schema exactly. Internally, Formik transforms rawYup validation errorson your behalf. If you are usingvalidate, then that function will determine theerrorsobjects shape. `values` `initialValues` `validationSchema` `validate` `errors` #### handleBlur: (e: any) => void `handleBlur: (e: any) => void` onBlurevent handler. Useful for when you need to track whether an input has beentouchedor not. This should be passed to `onBlur` `touched` `` #### handleChange: (e: React.ChangeEvent) => void `handleChange: (e: React.ChangeEvent) => void` General input change event handler. This will update thevalues[key]wherekeyis the event-emitting input'snameattribute. If thenameattribute is not present,handleChangewill look for an input'sidattribute. Note: "input" here means all HTML inputs. `values[key]` `key` `name` `name` `handleChange` `id` #### handleReset: () => void `handleReset: () => void` Reset handler. Will reset the form to its initial state. This should be passed to `` #### handleSubmit: (e: React.FormEvent) => void `handleSubmit: (e: React.FormEvent) => void` Submit handler. This should be passed to
...
. To learn more about the submission process, seeForm Submission. `
...
` #### isSubmitting: boolean `isSubmitting: boolean` Submitting state of the form. Returnstrueif submission is in progress andfalseotherwise. IMPORTANT: Formik will set this totrueas soon as submission isattempted. To learn more about the submission process, seeForm Submission. `true` `false` `true` #### isValid: boolean `isValid: boolean` Returnstrueif there are noerrors(i.e. theerrorsobject is empty) andfalseotherwise. `true` `errors` `errors` `false` Note:isInitialValidwas deprecated in 2.x. However, for backwards compatibility, if theisInitialValidprop is specified,isValidwill returntrueif the there are noerrors, or the result ofisInitialValidof the form if it is in "pristine" condition (i.e. notdirty). `isInitialValid` `isInitialValid` `isValid` `true` `errors` `isInitialValid` `dirty` #### isValidating: boolean `isValidating: boolean` Returnstrueif Formik is running validation during submission, or by calling[validateForm]directlyfalseotherwise. To learn more about what happens withisValidatingduring the submission process, seeForm Submission. `true` `validateForm` `false` `isValidating` #### resetForm: (nextState?: Partial>) => void `resetForm: (nextState?: Partial>) => void` Imperatively reset the form. The only (optional) argument,nextState, is an object on which any of theseFormikStatefields are optional: `nextState` `FormikState` ``` 1interfaceFormikState{2/** Form values */3values:Values;4/** map of field names to specific error for that field */5errors:FormikErrors;6/** map of field names to **whether** the field has been touched */7touched:FormikTouched;8/** whether the form is currently submitting */9isSubmitting:boolean;10/** whether the form is currently validating (prior to submission) */11isValidating:boolean;12/** Top level status state, in case you need it */13status?:any;14/** Number of times user tried to submit the form */15submitCount:number;16} ``` IfnextStateis specified, Formik will setnextState.valuesas the new "initial state" and use the related values ofnextStateto update the form'sinitialValuesas well asinitialTouched,initialStatus,initialErrors. This is useful for altering the initial state (i.e. "base") of the form after changes have been made. `nextState` `nextState.values` `nextState` `initialValues` `initialTouched` `initialStatus` `initialErrors` ``` 1// typescript usage2functionMyForm(props:MyFormProps){3// using TSX Generics here to set to 4return(56initialValues={props.initVals}7onSubmit={(values,actions)=>{8props.onSubmit(values).then(()=>{9actions.setSubmitting(false);10actions.resetForm({11values:{12// the type of `values` inferred to be Blog13title:'',14image:'',15body:'',16},17// you can also set the other form states here18});19});20}}21>22// etc23
24);25} ``` IfnextStateis omitted, then Formik will reset state to the original initial state. The latter is useful for callingresetFormwithincomponentDidUpdateoruseEffect. `nextState` `resetForm` `componentDidUpdate` `useEffect` ``` actions.resetForm(); ``` #### setErrors: (fields: { [field: string]: string }) => void `setErrors: (fields: { [field: string]: string }) => void` Seterrorsimperatively. `errors` #### setFieldError: (field: string, errorMsg: string) => void `setFieldError: (field: string, errorMsg: string) => void` Set the error message of a field imperatively.fieldshould match the key oferrorsyou wish to update. Useful for creating custom input error handlers. `field` `errors` #### setFieldTouched: (field: string, isTouched?: boolean, shouldValidate?: boolean) => Promise Set the touched state of a field imperatively.fieldshould match the key oftouchedyou wish to update. Useful for creating custom input blur handlers. Calling this method will trigger validation to run ifvalidateOnBluris set totrue(which it is by default).isToucheddefaults totrueif not specified. You can also explicitly prevent/skip validation by passing a third argument asfalse. `field` `touched` `validateOnBlur` `true` `isTouched` `true` `false` IfvalidateOnBluris set totrueand there are errors, they will be resolved in the returnedPromise. `validateOnBlur` `true` `Promise` #### submitForm: () => Promise `submitForm: () => Promise` Trigger a form submission. The promise will be rejected if form is invalid. #### submitCount: number `submitCount: number` Number of times user tried to submit the form. Increases whenhandleSubmitis called, resets after callinghandleReset.submitCountis readonly computed property and should not be mutated directly. `handleSubmit` `handleReset` `submitCount` #### setFieldValue: (field: string, value: React.SetStateAction, shouldValidate?: boolean) => Promise Set the value of a field imperatively.fieldshould match the key ofvaluesyou wish to update. Useful for creating custom input change handlers. Calling this will trigger validation to run ifvalidateOnChangeis set totrue(which it is by default). You can also explicitly prevent/skip validation by passing a third argument asfalse. `field` `values` `validateOnChange` `true` `false` IfvalidateOnChangeis set totrueand there are errors, they will be resolved in the returnedPromise. `validateOnChange` `true` `Promise` #### setStatus: (status?: any) => void `setStatus: (status?: any) => void` Set a top-levelstatusto anything you want imperatively. Useful for controlling arbitrary top-level state related to your form. For example, you can use it to pass API responses back into your component inhandleSubmit. `status` `handleSubmit` #### setSubmitting: (isSubmitting: boolean) => void `setSubmitting: (isSubmitting: boolean) => void` SetisSubmittingimperatively. You would call it withsetSubmitting(false)in youronSubmithandler to finish the cycle. To learn more about the submission process, seeForm Submission. `isSubmitting` `setSubmitting(false)` `onSubmit` #### setTouched: (fields: { [field: string]: boolean }, shouldValidate?: boolean) => Promise Settouchedimperatively. Calling this will trigger validation to run ifvalidateOnBluris set totrue(which it is by default). You can also explicitly prevent/skip validation by passing a second argument asfalse. `touched` `validateOnBlur` `true` `false` IfvalidateOnBluris set totrueand there are errors, they will be resolved in the returnedPromise. `validateOnBlur` `true` `Promise` #### setValues: (fields: React.SetStateAction<{ [field: string]: any }>, shouldValidate?: boolean) => Promise> Setvaluesimperatively. Calling this will trigger validation to run ifvalidateOnChangeis set totrue(which it is by default). You can also explicitly prevent/skip validation by passing a second argument asfalse. `values` `validateOnChange` `true` `false` IfvalidateOnChangeis set totrueand there are errors, they will be resolved in the returnedPromise. `validateOnChange` `true` `Promise` #### status?: any `status?: any` A top-level status object that you can use to represent form state that can't otherwise be expressed/stored with other methods. This is useful for capturing and passing through API responses to your inner component. statusshould only be modified by callingsetStatus. `status` `setStatus` #### touched: { [field: string]: boolean } `touched: { [field: string]: boolean }` Touched fields. Each key corresponds to a field that has been touched/visited. #### values: { [field: string]: any } `values: { [field: string]: any }` Your form's values. Will have the shape of the result ofmapPropsToValues(if specified) or all props that are not functions passed to your wrapped component. `mapPropsToValues` #### validateForm: (values?: any) => Promise> `validateForm: (values?: any) => Promise>` Imperatively call yourvalidateorvalidateSchemadepending on what was specified. You can optionally pass values to validate against and this modify Formik state accordingly, otherwise this will use the currentvaluesof the form. `validate` `validateSchema` `values` #### validateField: (field: string) => void `validateField: (field: string) => void` Imperatively call field'svalidatefunction if specified for given field or run schema validation usingYup'sschema.validateAtand the provided top-levelvalidationSchemaprop. Formik will use the current field value. `validate` `schema.validateAt` `validationSchema` ### component?: React.ComponentType> `component?: React.ComponentType>` ``` 1;23constContactForm=({4handleSubmit,5handleChange,6handleBlur,7values,8errors,9})=>(101118{errors.name&&
{errors.name}
}19Submit2021); ``` Warning:takes precedence overso don’t use both in the same. `` `` `` ### render: (props: FormikProps) => ReactNode `render: (props: FormikProps) => ReactNode` Deprecated in 2.x ``` 1}/>23(5613{errors.name&&14
15{errors.name}16
}17Submit1819)}20/> ``` ### children?: React.ReactNode | (props: FormikProps) => ReactNode `children?: React.ReactNode | (props: FormikProps) => ReactNode` ``` 1}/>23// or...456{({handleSubmit,handleChange,handleBlur,values,errors})=>(7815{errors.name&&16
17{errors.name}18
}19Submit2021)}22
``` ### enableReinitialize?: boolean `enableReinitialize?: boolean` Default isfalse. Control whether Formik should reset the form ifinitialValueschanges (using deep equality). `false` `initialValues` ### isInitialValid?: boolean `isInitialValid?: boolean` Deprecated in 2.x, useinitialErrorsinstead `initialErrors` Control the initial value ofisValidprop prior to mount. You can also pass a function. Useful for situations when you want to enable/disable a submit and reset buttons on initial mount. `isValid` ### initialErrors?: FormikErrors `initialErrors?: FormikErrors` Initial field errors of the form, Formik will make these values available to render methods component aserrors. `errors` Note:initialErrorsis not available to the higher-order componentwithFormik, usemapPropsToErrorsinstead. `initialErrors` `withFormik` `mapPropsToErrors` ### initialStatus?: any `initialStatus?: any` An arbitrary value for the initialstatusof the form. If the form is reset, this value will be restored. `status` Note:initialStatusis not available to the higher-order componentwithFormik, usemapPropsToStatusinstead. `initialStatus` `withFormik` `mapPropsToStatus` ### initialTouched?: FormikTouched `initialTouched?: FormikTouched` Initial visited fields of the form, Formik will make these values available to render methods component astouched. `touched` Note:initialTouchedis not available to the higher-order componentwithFormik, usemapPropsToTouchedinstead. `initialTouched` `withFormik` `mapPropsToTouched` ### initialValues: Values `initialValues: Values` Initial field values of the form, Formik will make these values available to render methods component asvalues. `values` Even if your form is empty by default, you must initialize all fields with initial values otherwise React will throw an error saying that you have changed an input from uncontrolled to controlled. Note:initialValuesnot available to the higher-order component, usemapPropsToValuesinstead. `initialValues` `mapPropsToValues` ### onReset?: (values: Values, formikBag: FormikBag) => void `onReset?: (values: Values, formikBag: FormikBag) => void` Your optional form reset handler. It is passed your formsvaluesand the "FormikBag". `values` ### onSubmit: (values: Values, formikBag: FormikBag) => void | Promise `onSubmit: (values: Values, formikBag: FormikBag) => void | Promise` Your form submission handler. It is passed your formsvaluesand the "FormikBag", which includes an object containing a subset of theinjected props and methods(i.e. all the methods with names that start withset+resetForm) and any props that were passed to the wrapped component. `values` `set` `resetForm` Note:errors,touched,statusand all event handlers are NOT included in theFormikBag. `errors` `touched` `status` `FormikBag` IMPORTANT: IfonSubmitis async, then Formik will automatically setisSubmittingtofalseon your behalf once it has resolved. This means you do NOT need to callformikBag.setSubmitting(false)manually. However, if youronSubmitfunction is synchronous, then you need to callsetSubmitting(false)on your own. `onSubmit` `isSubmitting` `false` `formikBag.setSubmitting(false)` `onSubmit` `setSubmitting(false)` ### validate?: (values: Values) => FormikErrors | Promise `validate?: (values: Values) => FormikErrors | Promise` Note: I suggest usingvalidationSchemaand Yup for validation. However,validateis a dependency-free, straightforward way to validate your forms. `validationSchema` `validate` Validate the form'svalueswith function. This function can either be: `values` - Synchronous and return anerrorsobject. `errors` ``` 1// Synchronous validation2constvalidate=values=>{3consterrors={};45if(!values.email){6errors.email='Required';7}elseif(!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)){8errors.email='Invalid email address';9}1011//...1213returnerrors;14}; ``` - Asynchronous and return a Promise that's resolves to an object containingerrors `errors` ``` 1// Async Validation2constsleep=ms=>newPromise(resolve=>setTimeout(resolve,ms));34constvalidate=values=>{5returnsleep(2000).then(()=>{6consterrors={};7if(['admin','null','god'].includes(values.username)){8errors.username='Nice try';9}10// ...11returnerrors;12});13}; ``` ### validateOnBlur?: boolean `validateOnBlur?: boolean` Default istrue. Use this option to run validations onblurevents. More specifically, when eitherhandleBlur,setFieldTouched, orsetTouchedare called. `true` `blur` `handleBlur` `setFieldTouched` `setTouched` ### validateOnChange?: boolean `validateOnChange?: boolean` Default istrue. Use this option to tell Formik to run validations onchangeevents andchange-related methods. More specifically, when eitherhandleChange,setFieldValue, orsetValuesare called. `true` `change` `change` `handleChange` `setFieldValue` `setValues` ### validateOnMount?: boolean `validateOnMount?: boolean` Default isfalse. Use this option to tell Formik to run validations when thecomponent mounts and/orinitialValueschange. `false` `` `initialValues` ### validationSchema?: Schema | (() => Schema) `validationSchema?: Schema | (() => Schema)` A Yup schemaor a function that returns a Yup schema. This is used for validation. Errors are mapped by key to the inner component'serrors. Its keys should match those ofvalues. `errors` `values` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/async-submission # Path: /docs/examples/async-submission #### Documentation #### API Reference #### Documentation #### API Reference # Async Submission Example This example demonstrates how to useasync/awaitto submit a Formik form. `async` `await` #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/basic # Path: /docs/examples/basic #### Documentation #### API Reference #### Documentation #### API Reference # Basic Example This example demonstrates how to use Formik in its most basic way. #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/checkboxes # Path: /docs/examples/checkboxes #### Documentation #### API Reference #### Documentation #### API Reference # Checkboxes Example This example demonstrates how to use Formik with a checkbox group. Given that the fields all share the samename, Formik will automagically bind them to a single array. `name` #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/dependent-fields-async-api-request # Path: /docs/examples/dependent-fields-async-api-request #### Documentation #### API Reference #### Documentation #### API Reference # Dependent fields with an Async API Request Example This is an example of a complex dependent field in Formik. In this example, one field's value is set by making an asynchronous API request based on the current values of other fields. #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/dependent-fields # Path: /docs/examples/dependent-fields #### Documentation #### API Reference #### Documentation #### API Reference # Dependent Fields Example This is an example of how to set the value of one field based on the current values of other fields in Formik. #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/field-arrays # Path: /docs/examples/field-arrays #### Documentation #### API Reference #### Documentation #### API Reference # Field Arrays Example This example demonstrates how to work with array fields in Formik. #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/instant-feedback # Path: /docs/examples/instant-feedback #### Documentation #### API Reference #### Documentation #### API Reference # Accessible Instant Feedback Example Instant feedback during typing can be extremely helpful in certain situations. For example, checking the validity (or availability) of a username shouldn't require the user to resubmit the form (multiple times). Providing instant feedback while users are typing can allow them to experiment more easily until they find valid input value (like a suitable username). Note: This isn't always optimal, use your judgement. #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/radio-group # Path: /docs/examples/radio-group #### Documentation #### API Reference #### Documentation #### API Reference # Radio Group Example This example demonstrates how to create a radio group with Formik. #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/typescript # Path: /docs/examples/typescript #### Documentation #### API Reference #### Documentation #### API Reference # Basic TypeScript This example demonstrates how to use Formik in its most basic way with TypeScript. #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/examples/with-material-ui # Path: /docs/examples/with-material-ui #### Documentation #### API Reference #### Documentation #### API Reference # Material UI Formik can be easily used/integrated withMaterial UI, with just passing a few formik props to the respective Material UI Component props. Refer to the example below to get started. #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/guides/arrays # Path: /docs/guides/arrays #### Documentation #### API Reference #### Documentation #### API Reference # Arrays and Nested Objects Formik has support for nested objects and arrays out of the box. These subjects are somewhat related because they both leverage the same syntax. ## Nested Objects Thenameprops in Formik can use lodash-like dot paths to reference nested Formik values. This means that you do not need to flatten out your form's values anymore. `name` ``` 1importReactfrom'react';2import{Formik,Form,Field}from'formik';34exportconstNestedExample=()=>(5
6

Social Profiles

7{15// same shape as initial values16console.log(values);17}}18>19
202122Submit232425
26); ``` ## Arrays Formik also has support for arrays and arrays of objects out of the box. Using lodash-like bracket syntax fornamestring you can quickly build fields for items in a list. `name` ``` 1importReactfrom'react';2import{Formik,Form,Field}from'formik';34exportconstBasicArrayExample=()=>(5
6

Friends

7{12// same shape as initial values13console.log(values);14}}15>16
171819Submit202122
23); ``` For more information around manipulating (add/remove/etc) items in lists, see the API reference section on thecomponent. `` ## Avoid nesting If you want to avoid this default behavior Formik also has support for it to have fields with dots. ``` 1importReactfrom'react';2import{Formik,Form,Field}from'formik';34exportconstNestedExample=()=>(5
6

Social Profiles

7{12// same shape as initial values13console.log(values);14}}15>16
1718Submit192021
22); ``` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/guides/form-submission # Path: /docs/guides/form-submission #### Documentation #### API Reference #### Documentation #### API Reference # Form Submission ## Submission Phases To submit a form in Formik, you need to somehow fire off the providedhandleSubmit(e)orsubmitFormprop. When you call either of these methods, Formik will execute the following(pseudo code)each time: `handleSubmit(e)` `submitForm` ### Pre-submit - Touch all fields.initialValuesare required and should always be specified. See#445 `initialValues` - SetisSubmittingtotrue `isSubmitting` `true` - IncrementsubmitCount+ 1 `submitCount` ### Validation - SetisValidatingtotrue `isValidating` `true` - Run all field-level validations,validate, andvalidationSchemaasynchronously and deeply merge results `validate` `validationSchema` - Are there any errors?Yes: Abort submission. SetisValidatingtofalse, seterrors, setisSubmittingtofalseNo: SetisValidatingtofalse, proceed to "Submission" - Yes: Abort submission. SetisValidatingtofalse, seterrors, setisSubmittingtofalse `isValidating` `false` `errors` `isSubmitting` `false` - No: SetisValidatingtofalse, proceed to "Submission" `isValidating` `false` ### Submission - Proceed with running the submission handler (i.e.onSubmitorhandleSubmit) `onSubmit` `handleSubmit` - Did the submit handler return a promise?Yes: Wait until it is resolved or rejected, then setsetSubmittingtofalseNo:CallsetSubmitting(false)to finish the cycle - Yes: Wait until it is resolved or rejected, then setsetSubmittingtofalse `setSubmitting` `false` - No:CallsetSubmitting(false)to finish the cycle `setSubmitting(false)` ## Frequently Asked Questions IfisValidatingisfalseandisSubmittingistrue. `isValidating` `false` `isSubmitting` `true` It is common practice to only show an input's errors in the UI if it has been visited (a.k.a "touched"). Before submitting a form, Formik touches all fields so that all errors that may have been hidden will now be visible. Disable whatever is triggering submission ifisSubmittingistrue. `isSubmitting` `true` IfisValidatingistrueandisSubmittingistrue. `isValidating` `true` `isSubmitting` `true` If the submission handler does not return a promise, make suresetSubmitting(false)is called at the end of the handler. `setSubmitting(false)` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/guides/react-native # Path: /docs/guides/react-native #### Documentation #### API Reference #### Documentation #### API Reference # React Native Formik is 100% compatible with React Native and React Native Web.However, because of differences between ReactDOM's and React Native's handling of forms and text input, there are some differences to be aware of. This section will walk you through them and what we consider to be best practices. ### The gist Before going any further, here's a super minimal gist of how to use Formik with React Native that demonstrates the key differences: ``` 1// Formik x React Native example2importReactfrom'react';3import{Button,TextInput,View}from'react-native';4import{Formik}from'formik';56exportconstMyReactNativeForm=props=>(7console.log(values)}10>11{({handleChange,handleBlur,handleSubmit,values})=>(1213181920)}21
22); ``` As you can see above, the notable differences between using Formik with React DOM and React Native are: - Formik'shandleSubmitis passed to a3233
3435);36}; ``` #### withFormik() `withFormik()` ``` 1importReactfrom'react';2import*asYupfrom'yup';3import{withFormik,FormikProps,FormikErrors,Form,Field}from'formik';45// Shape of form values6interfaceFormValues{7email:string;8password:string;9}1011interfaceOtherProps{12message:string;13}1415// Aside: You may see InjectedFormikProps instead of what comes below in older code.. InjectedFormikProps was artifact of when Formik only exported a HoC. It is also less flexible as it MUST wrap all props (it passes them through).16constInnerForm=(props:OtherProps&FormikProps)=>{17const{touched,errors,isSubmitting,message}=props;18return(19
20

{message}

2122{touched.email&&errors.email&&
{errors.email}
}232425{touched.password&&errors.password&&
{errors.password}
}262728Submit293031);32};3334// The type of props MyForm receives35interfaceMyFormProps{36initialEmail?:string;37message:string;// if this passed all the way through you might do this or make a union type38}3940// Wrap our form with the withFormik HoC41constMyForm=withFormik({42// Transform outer props into form values43mapPropsToValues:props=>{44return{45email:props.initialEmail||'',46password:'',47};48},4950// Add a custom validation function (this can be async too!)51validate:(values:FormValues)=>{52leterrors:FormikErrors={};53if(!values.email){54errors.email='Required';55}elseif(!isValidEmail(values.email)){56errors.email='Invalid email address';57}58returnerrors;59},6061handleSubmit:values=>{62// do submitting things63},64})(InnerForm);6566// Use wherevs67constBasic=()=>(68
69

My App

70

This can be anywhere in your application

7172
73);7475exportdefaultBasic; ``` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/guides/validation # Path: /docs/guides/validation #### Documentation #### API Reference #### Documentation #### API Reference # Validation Formik is designed to manage forms with complex validation with ease. Formik supports synchronous and asynchronous form-level and field-level validation. Furthermore, it comes with baked-in support for schema-based form-level validation through Yup. This guide will describe the ins and outs of all of the above. ## Flavors of Validation ### Form-level Validation Form-level validation is useful because you have complete access to all of your form'svaluesand props whenever the function runs, so you can validate dependent fields at the same time. `values` There are 2 ways to do form-level validation with Formik: - andwithFormik({ validate: ... }) `` `withFormik({ validate: ... })` - andwithFormik({ validationSchema: ... }) `` `withFormik({ validationSchema: ... })` #### validate `validate` andwithFormik()take a prop/option calledvalidatethat accepts either a synchronous or asynchronous function. `` `withFormik()` `validate` ``` 1// Synchronous validation2constvalidate=(values,props/* only available when using withFormik */)=>{3consterrors={};45if(!values.email){6errors.email='Required';7}elseif(!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)){8errors.email='Invalid email address';9}1011//...1213returnerrors;14};1516// Async Validation17constsleep=ms=>newPromise(resolve=>setTimeout(resolve,ms));1819constvalidate=(values,props/* only available when using withFormik */)=>{20returnsleep(2000).then(()=>{21consterrors={};22if(['admin','null','god'].includes(values.username)){23errors.username='Nice try';24}25// ...26returnerrors;27});28}; ``` For more information about, see the API reference. `` #### validationSchema `validationSchema` As you can see above, validation is left up to you. Feel free to write your own validators or use a 3rd party library. At The Palmer Group, we useYupfor object schema validation. It has an API that's pretty similar toJoiandReact PropTypesbut is small enough for the browser and fast enough for runtime usage. Because we ❤️ Yup sooo much, Formik has a special config option / prop for Yup object schemas calledvalidationSchemawhich will automatically transform Yup's validation errors into a pretty object whose keys matchvaluesandtouched. This symmetry makes it easy to manage business logic around error messages. `validationSchema` `values` `touched` To add Yup to your project, install it from NPM. ``` npm install yup --save ``` ``` 1importReactfrom'react';2import{Formik,Form,Field}from'formik';3import*asYupfrom'yup';45constSignupSchema=Yup.object().shape({6firstName:Yup.string()7.min(2,'Too Short!')8.max(50,'Too Long!')9.required('Required'),10lastName:Yup.string()11.min(2,'Too Short!')12.max(50,'Too Long!')13.required('Required'),14email:Yup.string().email('Invalid email').required('Required'),15});1617exportconstValidationSchemaExample=()=>(18
19

Signup

20{28// same shape as initial values29console.log(values);30}}31>32{({errors,touched})=>(33
3435{errors.firstName&&touched.firstName?(36
{errors.firstName}
37):null}3839{errors.lastName&&touched.lastName?(40
{errors.lastName}
41):null}4243{errors.email&&touched.email?
{errors.email}
:null}44Submit4546)}4748
49); ``` For more information about, see the API reference. `` ### Field-level Validation #### validate `validate` Formik supports field-level validation via thevalidateprop of/components oruseFieldhook. This function can be synchronous or asynchronous (return a Promise). It will run after anyonChangeandonBlurby default. This behavior can be altered at the top levelcomponent using thevalidateOnChangeandvalidateOnBlurprops respectively. In addition to change/blur, all field-level validations are run at the beginning of a submission attempt and then the results are deeply merged with any top-level validation results. `validate` `` `` `useField` `onChange` `onBlur` `` `validateOnChange` `validateOnBlur` Note: The/components'validatefunction will only be executed on mounted fields. That is to say, if any of your fields unmount during the flow of your form (e.g. Material-UI'sunmounts the previousyour user was on), those fields will not be validated during form validation/submission. `/` `validate` `` `` ``` 1importReactfrom'react';2import{Formik,Form,Field}from'formik';34functionvalidateEmail(value){5leterror;6if(!value){7error='Required';8}elseif(!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)){9error='Invalid email address';10}11returnerror;12}1314functionvalidateUsername(value){15leterror;16if(value==='admin'){17error='Nice try!';18}19returnerror;20}2122exportconstFieldLevelValidationExample=()=>(23
24

Signup

25{31// same shape as initial values32console.log(values);33}}34>35{({errors,touched,isValidating})=>(36
3738{errors.email&&touched.email&&
{errors.email}
}394041{errors.username&&touched.username&&
{errors.username}
}4243Submit4445)}4647
48); ``` ### Manually Triggering Validation You can manually trigger both form-level and field-level validation with Formik using thevalidateFormandvalidateFieldmethods respectively. `validateForm` `validateField` ``` 1importReactfrom'react';2import{Formik,Form,Field}from'formik';34functionvalidateEmail(value){5leterror;6if(!value){7error='Required';8}elseif(!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)){9error='Invalid email address';10}11returnerror;12}1314functionvalidateUsername(value){15leterror;16if(value==='admin'){17error='Nice try!';18}19returnerror;20}2122exportconstFieldLevelValidationExample=()=>(23
24

Signup

25{31// same shape as initial values32console.log(values);33}}34>35{({errors,touched,validateField,validateForm})=>(36
3738{errors.email&&touched.email&&
{errors.email}
}394041{errors.username&&touched.username&&
{errors.username}
}42{/** Trigger field-level validation43imperatively */}44validateField('username')}>45Check Username4647{/** Trigger form-level validation48imperatively */}49validateForm().then(()=>console.log('blah'))}52>53Validate All5455Submit5657)}5859
60); ``` ## When Does Validation Run? You can control when Formik runs validation by changing the values ofand/orprops depending on your needs. By default, Formik will run validation methods as follows: `` `` After "change" events/methods(things that updatevalues) `values` - handleChange `handleChange` - setFieldValue `setFieldValue` - setValues `setValues` After "blur" events/methods(things that updatetouched) `touched` - handleBlur `handleBlur` - setTouched `setTouched` - setFieldTouched `setFieldTouched` Whenever submission is attempted - handleSubmit `handleSubmit` - submitForm `submitForm` There are also imperative helper methods provided to you via Formik's render/injected props which you can use to imperatively call validation. - validateForm `validateForm` - validateField `validateField` ## Displaying Error Messages Error messages are dependent on the form's validation. If an error exists, and the validation function produces an error object (as it should) with a matching shape to our values/initialValues, dependent field errors can be accessed from the errors object. ``` 1importReactfrom'react';2import{Formik,Form,Field}from'formik';3import*asYupfrom'yup';45constDisplayingErrorMessagesSchema=Yup.object().shape({6username:Yup.string()7.min(2,'Too Short!')8.max(50,'Too Long!')9.required('Required'),10email:Yup.string().email('Invalid email').required('Required'),11});1213exportconstDisplayingErrorMessagesExample=()=>(14
15

DisplayingErrorMessages

16{23// same shape as initial values24console.log(values);25}}26>27{({errors,touched})=>(28
2930{/* If this field has been touched, and it contains an error, display it31*/}32{touched.username&&errors.username&&
{errors.username}
}3334{/* If this field has been touched, and it contains an error, display35it */}36{touched.email&&errors.email&&
{errors.email}
}373839)}4041
42); ``` TheErrorMessagecomponent can also be used to display error messages. ## Frequently Asked Questions IfisValidatingprop istrue `isValidating` `true` No. Useundefinedinstead. Formik usesundefinedto represent empty states. If you usenull, several parts of Formik's computed props (e.g.isValidfor example), will not work as expected. `undefined` `undefined` `null` `isValid` Formik has extensive unit tests for Yup validation so you do not need to test that. However, if you are rolling your own validation functions, you should simply unit test those. If you do need to test Formik's execution you should use the imperativevalidateFormandvalidateFieldmethods respectively. `validateForm` `validateField` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/migrating-v2 # Path: /docs/migrating-v2 #### Documentation #### API Reference #### Documentation #### API Reference # Migrating from v1.x to v2.x ## Breaking Changes ### Minimum Requirements - Since Formik 2 is built on top of React Hooks, you must be on React 16.8.x or higher - Since Formik 2 uses theunknowntype, you must be on TypeScript 3.0 or higher (if you use TypeScript) `unknown` There are a few breaking changes in Formik 2.x.Luckily, these probably won't impact many people: ### resetForm `resetForm` With Formik 2, we introduced the new props for more initial state:initialErrors,initialTouched,initialStatus. Therefore,resetForm's signature has changed. Instead of optionally accepting just the next initial values of the form. It now optionally accepts the partial next initial state of Formik. `initialErrors` `initialTouched` `initialStatus` `resetForm` v1 ``` 1// Reset to `initialValues`2formik.resetForm();3// Reset form and set the next `initialValues` of the form4formik.resetForm({name:'',email:''}); ``` v2 ``` 1// Reset the form. This will set the next initial state of2// Formik to the `initialValues`, `initialErrors`, `initialTouched`,3// `initialStatus` props.4formik.resetForm();56// Reset the form back to `initialXXXX` but change next7// `initialValues` to a custom value8formik.resetForm({9values:{name:'Custom initial values',email:''},10});1112// Reset form back to `initialXXXX`, but change next `initialValues`13// and `initialErrors` of the form14formik.resetForm({15values:{name:'',email:''},16errors:{name:'Something special'},17});1819// Reset form back to `initialXXXX`, but change next `initialStatus` to 'Foo'20formik.resetForm({21status:'Foo',22}); ``` ### setError `setError` This method has been deprecated for a while with a warning in v1.x releases. It's fully removed in v2. Please use Formik'ssetStatus(status)instead. It works identically. Note: this is/was notsetErrors(plural) which is still around. `setStatus(status)` `setErrors` ### validate `validate` As you may know, you can return a Promise of a validation error fromvalidate. In 1.x, it didn't matter if this promise is resolved or rejected as in both cases the payload of the promise was interpreted as the validation error. In 2.x, rejection will be interpreted as an actual exception and it won't update the form error state. Any validation function that returns a rejected promise of errors needs to be adjusted to return a resolved promise of errors instead. `validate` ### ref `ref` Currently, you can't attach a ref to Formik using therefprop. However, you still can get around this issue using the propinnerRef. We have some WIP#2208to instead useReact.forwardRef. `ref` `innerRef` `React.forwardRef` ### isValid `isValid` This property does not take the value ofdirtyinto account anymore. This means that if you want to disable a submit button when the form is notdirty(i.e. on first render and when values are unchanged), you have to explicitly check for it. `dirty` `dirty` ``` 12Submit3 ``` ### Typescript changes #### FormikActions `FormikActions` FormikActionshas been renamed toFormikHelpersIt should be a straightforward change to import or alias the type `FormikActions` `FormikHelpers` v1 ``` import{FormikActions}from'formik'; ``` v2 ``` import{FormikHelpersasFormikActions}from'formik'; ``` #### FieldProps `FieldProps` FieldPropsnow accepts two generic type parameters.Both parameters are optional, butFormValueshas been moved from the first to the second parameter. `FieldProps` `FormValues` v1 ``` typeProps=FieldProps; ``` v2 ``` typeProps=FieldProps; ``` ## What's New? ### Checkboxes and Select multiple Similarly to Angular, Vue, or Svelte, Formik 2 "fixes" React checkboxes and multi-selects with built-in array binding and boolean behavior. This was one of the most confusing things for people in Formik 1.x. ``` 1importReactfrom'react';2import{Formik,Field,Form}from'formik';3import{Debug}from'./Debug';45constsleep=ms=>newPromise(resolve=>setTimeout(resolve,ms));67constCheckboxExample=()=>(8
9

Checkboxes

10

11This example demonstrates how to properly create checkboxes with Formik.12

13{22awaitsleep(1000);23alert(JSON.stringify(values,null,2));24}}25>26{({isSubmitting,getFieldProps,handleChange,handleBlur,values})=>(27
28{/*29This first checkbox will result in a boolean value being stored.30*/}31Basic Info
3236{/*37Multiple checkboxes with the same name attribute, but different38value attributes will be considered a "checkbox group". Formik will automagically39bind the checked values to a single array for your benefit. All the add and remove40logic will be taken care of for you.41*/}4243What best describes you? (check all that apply)4445495357{/*58You do not _need_ to use /useField to get this behavior,59using handleChange, handleBlur, and values works as well.60*/}617273{/*74The 234// 567// 232425// 26 ``` ### getFieldProps(nameOrProps) `getFieldProps(nameOrProps)` There are two useful additions toFormikProps,getFieldPropsandgetFieldMeta. These are Kent C. Dodds-esque prop getters that can be useful if you love prop drilling, arenotusing the context-based API's, or if you are building a customuseField. `FormikProps` `getFieldProps` `getFieldMeta` `useField` ``` 1exportinterfaceFieldInputProps{2/** Value of the field */3value:Value;4/** Name of the field */5name:string;6/** Multiple select? */7multiple?:boolean;8/** Is the field checked? */9checked?:boolean;10/** Change event handler */11onChange:FormikHandlers['handleChange'];12/** Blur event handler */13onBlur:FormikHandlers['handleBlur'];14} ``` ### getFieldMeta(name) `getFieldMeta(name)` Given a name it will return an object: ``` 1exportinterfaceFieldMetaProps{2/** Value of the field */3value:Value;4/** Error message of the field */5error?:string;6/** Has the field been visited? */7touched:boolean;8/** Initial value of the field */9initialValue?:Value;10/** Initial touched state of the field */11initialTouched:boolean;12/** Initial error message of the field */13initialError?:string;14} ``` ### Misc - FormikContextis now exported `FormikContext` - validateOnMount?: boolean = false `validateOnMount?: boolean = false` - initialErrors,initialTouched,initialStatushave been added `initialErrors` `initialTouched` `initialStatus` ## Deprecation Warnings ### Allrenderprops have been deprecated with a console warning. `render` For,,,, therenderprop has been deprecated with a warning as it will be removed in future versions. Instead, use a child callback function. This deprecation is meant to parallel React Context Consumer's usage. `` `` `` `` `render` ``` 1- ....} />2+{props => ... } ``` #### On this page #### Resources - Docs - Learn - Guides - API Reference - Blog #### Community - User Showcase - Funding - Community Chat - Project Forum - Releases - Star #### About Formium - Home - GitHub - Twitter - Contact Sales #### Subscribe to our newsletter The latest Formik news, articles, and resources, sent to your inbox. --- # Formik Documentation # Source: https://formik.org/docs/overview # Path: /docs/overview #### Documentation #### API Reference #### Documentation #### API Reference # Overview Let's face it, forms are really verbose inReact. To make matters worse, most form helpers do wayyyy too much magic and often have a significant performance cost associated with them. Formik is a small library that helps you with the 3 most annoying parts: - Getting values in and out of form state - Validation and error messages - Handling form submission By colocating all of the above in one place, Formik will keep things organized--making testing, refactoring, and reasoning about your forms a breeze. ## Motivation I (@jaredpalmer) wrote Formik while building a large internal administrative dashboard with@eonwhite. With around ~30 unique forms, it quickly became obvious that we could benefit by standardizing not just our input components but also the way in which data flowed through our forms. ### Why not Redux-Form? By now, you might be thinking, "Why didn't you just useRedux-Form?" Good question. - According to our prophet Dan Abramov,form state is inherently ephemeral and local, so tracking it in Redux (or any kind of Flux library) is unnecessary - Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY SINGLE KEYSTROKE. This is fine for small apps, but as your Redux app grows, input latency will continue to increase if you use Redux-Form. - Redux-Form is 22.5 kB minified gzipped (Formik is 12.7 kB) My goal with Formik was to create a scalable, performant, form helper with a minimal API that does the really really annoying stuff, and leaves the rest up to you. My talk at React Alicante goes much deeper into Formik's motivation and philosophy, introduces the library (by watching me build a mini version of it), and demos how to build a non-trivial form (with arrays, custom inputs, etc.) using the real thing. ## Influences Formik started by expanding onthis little higher order componentbyBrent Jackson, some naming conventions from Redux-Form, and (most recently) the render props approach popularized byReact-MotionandReact-Router 4. Whether you have used any of the above or not, Formik only takes a few minutes to get started with. ## Installation You can install Formik withNPM,Yarn, or a good ol'