0% found this document useful (0 votes)
52 views

Forms With Formik + TypeScript

One of the most painful topics for React developers always was how to build nice forms and have a nice clean code.

Uploaded by

jmanzura
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Forms With Formik + TypeScript

One of the most painful topics for React developers always was how to build nice forms and have a nice clean code.

Uploaded by

jmanzura
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

4/9/2019 Forms with Formik + TypeScript – fotonTech – Medium

Forms with Formik + TypeScript


Leonardo Maldonado Follow
Feb 26 · 3 min read

One of the most painful topics for React developers always was how to
build nice forms and have a nice clean code. Some people might think
that it’s not necessary to use a third-party library, but in some cases,
that’s needed especially when we need more complex forms. First, we
started with Redux Form, a lot of people used it for a long time but then
we started to ask ourselves if it’s a good idea and the best way to
manage our form state using our Redux store. We don’t need to have
our form state in our Redux store, it’s such a not good practice at all.

Then, Formik really came to change it for us and let our forms so easy
to build and our code so readable and well-written that now we don’t
have to worry too much about it. We know that Formik code is written
in TypeScript but a lot of people still don’t know how to use it the right
way.

So, in this article, we’re going to learn about how to use Formik with
TypeScript, since a lot of developers has been started to use it lately,
let’s jump into this hype and see how we can improve more our forms.

https://medium.com/fotontech/forms-with-formik-typescript-d8154cc24f8a 1/8
4/9/2019 Forms with Formik + TypeScript – fotonTech – Medium

Starting
First, let’s start installing some dependencies:

yarn add formik yup @types/yup

Now, we’re going to start to build our form importing some things that
we’re going to need: we’re going to import the withFormik HOC that
passes our props and form handlers, and also import the FormikProps .
We’re going also import yup to validate our fields.

1 import { withFormik, FormikProps } from "formik";


2 import * as Yup from "yup";

Now, to start to build our forms, we need first define some interfaces.
Let’s defined an interface called FormValues that’s going to define all
the values that we’re going to have in our form:

1 interface FormValues {
2 email: string;
3 password: string;
4 }

We’ll also define other interface called OtherProps , that in case we


want to pass other props to our component. In our case, we’re going to
pass a property called title :

1 interface OtherProps {
2 title?: string;
3 }

Our last interfaces it’s going to be called MyFormProps , and with that
interface, we can define some properties for our initial values, in case
we want to have some initial values.

https://medium.com/fotontech/forms-with-formik-typescript-d8154cc24f8a 2/8
4/9/2019 Forms with Formik + TypeScript – fotonTech – Medium

1 interface MyFormProps {
2 initialEmail?: string;
3 initialPassword?: string;
4 }

Now, we’re going to write our component called InnerForm , pass the
interfaces that we created, and also put some extra code:

https://medium.com/fotontech/forms-with-formik-typescript-d8154cc24f8a 3/8
4/9/2019 Forms with Formik + TypeScript – fotonTech – Medium

1 const InnerForm = (props: OtherProps & FormikProps<FormValu


2 const {
3 values,
4 errors,
5 touched,
6 handleChange,
7 handleBlur,
8 handleSubmit,
9 isSubmitting,
10 title
11 } = props;
12
13 return (
14 <Wrapper>
15 <h1>{title}</h1>
16 <form onSubmit={handleSubmit}>
17 <InputWrapper>
18 <Label>Email</Label>
19 <Input
20 width={50}
21 type="email"
22 name="email"
23 onChange={handleChange}
24 onBlur={handleBlur}
25 value={values.email}
26 />
27 </InputWrapper>
28
29 <InputWrapper>
30 <Label>Password</Label>
31 <Input
32 width={50}
33 type="password"
34 name="password"
35 onChange={handleChange}

We passed our props with OtherProps and we also wrapped our


FormValues inside the FormikProps . The rest of the code it’s pretty
self-explained, now we’re going to create our final component wrapped
with the withFormik HOC.

https://medium.com/fotontech/forms-with-formik-typescript-d8154cc24f8a 4/8
4/9/2019 Forms with Formik + TypeScript – fotonTech – Medium

First, let’s write our component called App and pass the MyFormProps

and FormValues inside the withFormik.

1 const App = withFormik<MyFormProps, FormValues>({


2 ...

Now, inside our wrapped component, inside our mapPropsToValues

method, if we want to pass an initial value to one of our fields, we can,


or we can just pass an empty string.

1 mapPropsToValues: props => ({


2 email: props.initialEmail || "",
3 password: props.initialPassword || ""
4 })

We’re going to use yup to validate our fields so after the


mapPropsToValues method, let’s put the following code:

1 validationSchema: Yup.object().shape({
2 email: Yup.string()
3 .email("Email not valid")
4 .required("Email is required"),
5 password: Yup.string().required("Password is require

Now, let’s write the handleSubmit function and also pass the
FormValues to validate our props.

1 handleSubmit({ email, password }: FormValues, { props, setSu


2 console.log(email, password);
3 }

Pretty simple, now our whole App component should look like this:

https://medium.com/fotontech/forms-with-formik-typescript-d8154cc24f8a 5/8
4/9/2019 Forms with Formik + TypeScript – fotonTech – Medium

1 const App = withFormik<MyFormProps, FormValues>({


2 mapPropsToValues: props => ({
3 email: props.initialEmail || "",
4 password: props.initialPassword || ""
5 }),
6
7 validationSchema: Yup.object().shape({
8 email: Yup.string()
9 .email("Email not valid")
10 .required("Email is required"),
11 password: Yup.string().required("Password is requir
12 }),
13
14 handleSubmit(

You can find all the code from this article here.

Conclusion
As you can see, Formik is a really helpful lib to let us write better forms
and let our code more readable.

This is a simple example of how to use Formik with TypeScript, but you
can improve it and use it the way you want. The goal here is to show
how to use it the best way and let our code strongly-typed and safer.

Thanks for the reading!

https://medium.com/fotontech/forms-with-formik-typescript-d8154cc24f8a 6/8

You might also like