Quantcast
Channel: Krzysztof Żuraw blog's RSS Feed
Viewing all articles
Browse latest Browse all 205

Formik - useFormikContext and useField hooks

$
0
0

As I’m using Formik to build forms inside React applications below there are some patterns you may enjoy.

Form

Let’s say that you have a form build using formik:

import React,{ FunctionComponent }from'react';import{ Formik, FieldProps, Field }from'formik';type FormValues ={
  name:string;
  email:string;};const UserForm: React.FunctionComponent=()=>{return(<Formik<FormValues>
      initalValues={{ name:'', email:''}}
      onSubmit={(values)=>sendDataToAPI(values)}>{(props)=>(<formonSubmit={props.onSubmit}><Fieldname="name">{({ field }: FieldProps<FormValues>) =><CustomInput{...field}/>}
          </Field><Fieldname="email">{({ field }: FieldProps<FormValues>) =><CustomInput{...field}/>}
          </Field></form>
      )}
    </Formik>
  );
};

const CustomInput: React.FunctionComponent<JSX.IntrinsicElements['input']> = ({ ...props }) => (
  <input{...props}/>
);

useField

I want to start with useField. Previously to create a field in formik you have to first create a Field component and then pass children render prop:

import{ FieldProps, Field }from'formik';<Fieldname="name">{({ field }: FieldProps<FormValues>) =><CustomInput{...field}/>}</Field>;

In 2.0.0 version maintainers introduced a new hook useField. It can be use to abstract that Field underneath is CustomInput:

import React,{ FunctionComponent }from'react';import{ useField }from'formik';const FormikCustomInput: React.FunctionComponent<{ name:string}>=({ name })=>{const[field]=useField(name);return<CustomInput{...field}/>;};

And then use it inside UserForm:

<formonSubmit={props.onSubmit}><FormikCustomInputname="name"/><FormikCustomInputname="email"/></form>

Where you can use it? In a place where you have multiple forms that use the same Fields.

useFormikContext

Another addition is useFormikContext. This is a Formik hook to get formikBag (formik values, errors and helpers) in your component. In previous versions you had to use connect to get your component into Formik context. Thanks to this new hook - there is no need for that. Where it can be useful? Inside nested forms when you don’t want to have prop drilling problem.

Summary

Formik added two new hooks: useField and useFormikContext to ease creating reusable and nested forms. Be sure to check them out!


Viewing all articles
Browse latest Browse all 205

Trending Articles