How to use useFormik() in Typescript?

Viewed 1419

Is it possible to use the useFormik() hook in TypeScript, and if so how would I convert the code below?

I have a simple form that I want to duplicate in a TypeScript app:


import React from 'react';
import * as Yup from 'yup';

import { Form, TextInput, Button } from './some/location';

const QuerySearch = () => {
  const { handleChange, handleBlur, values } = useFormik({
    initialValues: {
      query: '',
    },
    validationSchema: Yup.object({
      query: Yup.string(),
    }),
  });


  return (
    <Form action="/some-url">
      <TextInput
        required
        id="query"
        name="query"
        onChange={handleChange}
        onBlur={handleBlur}
        placeholder="Enter your query"
        value={values.query}
      
      />
      <Button type="submit">
        Text
      </Button>
    </Form>
  );
};

export default QuerySearch;

The Formik docs have a page on using TypeSript using withFormik and FormikProps, but it's quite verbose and I'd much prefer to stick with the useFormik() hook if possible.

For reference, the error messages I get are:

ERROR in src/components/some/file.tsx:48:58

TS2345: Argument of type '{ initialValues: { postcode: string; }; validationSchema: OptionalObjectSchema<{ postcode: Yup.StringSchema<string | undefined, Record<string, any>, string | undefined>; }, Record<string, any>, TypeOfShape<...>>; }' is not assignable to parameter of type 'FormikConfig<{ postcode: string; }>'.

Property 'onSubmit' is missing in type '{ initialValues: { postcode: string; }; validationSchema: OptionalObjectSchema<{ postcode: Yup.StringSchema<string | undefined, Record<string, any>, string | undefined>; }, Record<string, any>, TypeOfShape<...>>; }' but required in type 'FormikConfig<{ postcode: string; }>'.

I haven't added an interface for query as I wanted to produce the error messages in full.

2 Answers

I got it to work using:

const { handleChange, handleBlur, values } = useFormik<{
    query: string;
  }>({
    initialValues: {
      query: '',
    },
    onSubmit: (): void => {},
    validationSchema: Yup.object().shape({
      query: Yup.string(),
    }),
  });

onSubmit is superfluous here as submission is handled by the <form>'s action attribute, however it is "required in type 'FormikConfig'".

for the yup validation schema you need to use

Yup.object().shape({
  query: Yup.string()
})
Related