Written by: Geoffrey Callaghan

Forms with Formik and TypeScript

Forms With Formik And Typescript

Creating forms with Formik and TypeScript can enhance both the development experience and the robustness of your forms. Formik is a popular form library for React that simplifies form handling and validation. Integrating it with TypeScript allows you to leverage static typing to catch errors early and improve code readability.

Here’s a step-by-step guide to creating forms using Formik and TypeScript:

Step 1: Setting up the project

  1. Create a new React project with TypeScript:

    npx create-react-app my-form-app --template typescript
    cd my-form-app
  2. Install Formik and Yup (for validation):

    npm install formik yup

Step 2: Create a Form Component

  1. Create a new component file:

    Create MyForm.tsx in the src directory.

  2. Define your form values and validation schema:

    // src/MyForm.tsx
    import React from 'react';
    import { Formik, Form, Field, ErrorMessage } from 'formik';
    import * as Yup from 'yup';
    
    interface MyFormValues {
      name: string;
      email: string;
      age: number;
    }
    
    const initialValues: MyFormValues = {
      name: '',
      email: '',
      age: 0,
    };
    
    const validationSchema = Yup.object({
      name: Yup.string()
        .required('Name is required'),
      email: Yup.string()
        .email('Invalid email address')
        .required('Email is required'),
      age: Yup.number()
        .required('Age is required')
        .min(1, 'Age must be greater than zero')
    });
  3. Create the form component:

    const MyForm: React.FC = () => {
      return (
        <Formik
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={(values, actions) => {
            console.log(values);
            actions.setSubmitting(false);
          }}
        >
          {({ isSubmitting }) => (
            <Form>
              <div>
                <label htmlFor="name">Name</label>
                <Field id="name" name="name" type="text" />
                <ErrorMessage name="name" component="div" />
              </div>
    
              <div>
                <label htmlFor="email">Email</label>
                <Field id="email" name="email" type="email" />
                <ErrorMessage name="email" component="div" />
              </div>
    
              <div>
                <label htmlFor="age">Age</label>
                <Field id="age" name="age" type="number" />
                <ErrorMessage name="age" component="div" />
              </div>
    
              <button type="submit" disabled={isSubmitting}>
                Submit
              </button>
            </Form>
          )}
        </Formik>
      );
    };
    
    export default MyForm;

Step 3: Use the Form Component in your App

  1. Modify App.tsx to include your new form component:

    // src/App.tsx
    import React from 'react';
    import MyForm from './MyForm';
    
    const App: React.FC = () => {
      return (
        <div className="App">
          <h1>My Form</h1>
          <MyForm />
        </div>
      );
    };
    
    export default App;

Explanation

  • Typescript Interfaces: MyFormValues interface defines the shape of our form values, ensuring type safety.
  • Formik and Yup: Formik’s Formik component manages form state and handles submission. Yup is used to define a validation schema.
  • Field and ErrorMessage: Formik’s Field component connects the input fields to Formik’s state, and ErrorMessage displays validation errors.

Step 4: Running the Application

Run the following command to start the development server:

npm start

This will launch your React application, and you should see your form with the name, email, and age fields, along with validation.

By following these steps, you’ve created a robust form using Formik and TypeScript, ensuring both type safety and easy form handling and validation.