Introduction
Formik and Ant Design are robust tools that can streamline the design and form management in React.
Ant Design is a comprehensive UI framework with a rich set of pre-styled components.
Formik is a famous form state management library in the React ecosystem that simplifies form handling, validation, and submission. With the help of Yup, you can easily add validation to each field of your form managed by Formik.
In this guide, I will walk you through the step-by-step process of integrating Formik with Ant Design.
Step 1: Setting Up our React Project
We will create a new React Project using Vite with the support of TypeScript.
Type the command below to create a boilerplate:
npm create vite@latest antd-app -- --template react-ts
Go inside the project folder and install the necessary dependencies:
cd antd-app npm install
Step 2: Install Ant Design, Formik, and Yup
Here is the command to install all the modules:
npm install formik antd yup
Step 3: Creating Reusable Form Field Component
Inside the src folder, create a new folder called components.
Inside the components folder, create a new file called FormField.tsx and add the below code in it:
// src/components/FormField.tsx import React from "react"; import { Field, FieldProps } from "formik"; import { Form, Input } from "antd"; interface FormFieldProps { label: string; name: string; type?: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any component?: React.ComponentType<any>; } const FormField: React.FC<FormFieldProps> = ({ label, name, type = "text", component: Component = Input, }) => ( <Field name={name}> {({ field, meta }: FieldProps) => ( <Form.Item label={label} validateStatus={meta.touched && meta.error ? "error" : ""} help={meta.touched && meta.error ? meta.error : null} style={{ marginBottom: "1rem" }} > <Component {...field} type={type} /> </Form.Item> )} </Field> ); export default FormField;
In this code, we created a reusable FormField component form field that integrates Formik for state management and validation with Ant Design for styling and layout.
It allows for customization of the input type and component while handling error states and messages.
Step 4: Defining Form Values Type
Create a new folder called “types” under the “src” folder.
Inside the types folder, create a new file called “formTypes.tsx” and add the code below:
// src/types/formTypes.ts export interface FormValues { username: string; email: string; password: string; }
Step 5: Creating a Validation Schema Hook
Create a new folder called “hooks” inside the “src” folder.
Create a new file named useValidationSchema.ts under the hooks folder and add the below code:
// src/hooks/useValidationSchema.ts import * as Yup from "yup"; const useValidationSchema = () => { return Yup.object({ username: Yup.string().required("Username is required"), email: Yup.string() .email("Invalid email format") .required("Email is required"), password: Yup.string() .required("Password is required") .min(8, "Password must be at least 8 characters long"), }); }; export default useValidationSchema;
Step 6: Adding Form Styles
Create a new folder called “styles” inside the “src” folder.
Create a new file named formStyles.ts under the styles folder and add the below code:
// src/styles/formStyles.ts import { CSSProperties } from "react"; export const formContainer: CSSProperties = { maxWidth: 400, margin: "2rem auto", padding: "2rem", border: "1px solid #eaeaea", borderRadius: "8px", boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)", }; export const formTitle: CSSProperties = { textAlign: "center", marginBottom: "1.5rem", }; export const submitButton: CSSProperties = { width: "100%", };
Step 7: Creating the Signup Form Component
Inside the components folder, create a new file called SignupForm.tsx and add the code below:
// src/components/SignupForm.tsx import { Formik, FormikHelpers, Form as FormikForm } from "formik"; import { Form, Button, Input } from "antd"; import FormField from "./FormField"; import useValidationSchema from "../hooks/useValidationSchema"; import { FormValues } from "../types/formTypes"; import { formContainer, formTitle, submitButton } from "../styles/formStyles"; const SignupForm: React.FC = () => { const initialValues: FormValues = { username: "", email: "", password: "" }; const validationSchema = useValidationSchema(); const handleSubmit = ( values: FormValues, formikHelpers: FormikHelpers<FormValues> ) => { aler(JSON.stringify(values, null, 2)); formikHelpers.setSubmitting(false); }; return ( <div style={formContainer}> <h2 style={formTitle}>Signup Form</h2> <Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={handleSubmit} > {({ handleSubmit }) => ( <FormikForm onSubmit={handleSubmit}> <FormField label="Username" name="username" component={Input} /> <FormField label="Email" name="email" type="email" component={Input} /> <FormField label="Password" name="password" type="password" component={Input.Password} /> <Form.Item> <Button type="primary" htmlType="submit" style={submitButton}> Submit </Button> </Form.Item> </FormikForm> )} </Formik> </div> ); }; export default SignupForm;
In this code, we created a functional component called “SignupForm”. This component uses the custom FormField component we created for username, email, and password inputs.
In short, we created a complete signup form with validation, leveraging Formik for form state management and Ant Design for UI components. When we submit the form with valid input values, it will show an alert displaying all the form values in JSON format.
Step 8: Updating App.tsx file
Update the src/App.tsx file to include the SignupForm component:
// src/App.tsx import SignupForm from './components/SignupForm'; const App: React.FC = () => ( <div style={{ padding: '2rem' }}> <SignupForm /> </div> ); export default App;
And also, update the src/main.tsx file like this:
// src/main.tsx import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App.tsx"; ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <App /> </React.StrictMode> );
Here is the complete project structure of our application:
src/ components/ FormField.tsx SignupForm.tsx hooks/ useValidationSchema.ts styles/ formStyles.ts types/ formTypes.ts App.tsx main.tsx
Step 9: Run the project
Start the development server using the command below:
npm run dev
Go to this URL: http://localhost:5173/, and it will look like the below image:
We also added validation for each input field, and if it fails, the validation message looks like the below image:
If we fill the form with valid values, it will display an alert printing all the form values like this:
Conclusion
In this step-by-step guide, we have covered how to set up a new React project in Vite with TypeScript support, install and set up an Ant design, add validation and display error messages, and handle form submissions.
Formik allows us to manage the form value, and Yup defines our validation schema. By integrating formik with Ant design, we can create a visually appealing, validation-proof web form that will be very easy to manage.