Number field
In this tutorial, we will use Tailwind CSS and Formik to create the Number Field component. It will used a lot of in our forms like: Sign in form, sign up form, Contact us form, ...
1. Setup codes
Before add the NumberField, we need to add the TextField first, you can see in this link.
Create a new file components/common/forms/NumberField.tsx and add this code below
jsximport React from "react"; import TextField from "./TextField"; export default function NumberField({ id, name, label, maxLength, }: { id: string; name: string; label?: string; maxLength?: number; }) { return ( <> <TextField id={id} name={name} type="number" label={label} maxLength={maxLength} /> </> ); }
2. Usages
Because the NumberField component is built base on Formik, so we need to wrap the Formik and Form tags out site of NumberField component.
jsx"use client"; import { Form, Formik } from "formik"; ... <Formik initialValues={{ age: "" }} validationSchema={validationSchema} onSubmit={(values) => alert(`Age is ${values.age}`)} > <Form> <NumberField id="age" name="age" label="User age" /> .... </Form> </Formik>
You can see the UI like this
Form with Number Field
You can see all the source code
jsx"use client"; import { Form, Formik } from "formik"; import React from "react"; import * as Yup from "yup"; import Button from "@/components/Button"; import NumberField from "@/components/Form/NumberField"; const validationSchema = Yup.object().shape({ age: Yup.number().required("Age is required").moreThan(0, "Age must be greater than 0"), }); const TestingForm = () => { return ( <div className="not-prose flex max-w-2xl flex-col gap-3 rounded-lg border-2 p-6"> <p className="mb-4 text-3xl font-bold">Form with Number Field</p> <Formik initialValues={{ age: "" }} validationSchema={validationSchema} onSubmit={(values) => alert(`Age is ${values.age}`)} > <Form> <NumberField id="age" name="age" label="User age" /> <div className="mt-6"> <Button type="submit" className="w-full"> <span> Submit <span aria-hidden="true">→</span> </span> </Button> </div> </Form> </Formik> </div> ); }; export default TestingForm;
Learn more to using NumberField component in Signin, Signup forms on this link
You can get all my components in here -->