Form validation is a critical part of web development. It ensures that user input is correct, complete, and meets specific requirements.
In this article, weβll take a look at some of the most popular solutions for form management and validation in React:
1. React Hook Form
React Hook Form is a library that simplifies form handling in React with hooks and HTML standard. It minimizes re-renders, validation computation and mounting time, and supports.
The best React form library that I have ever used while building a react app because of its utility and simplicity. It has a lot of useful tools and doesnβt require much code compared to Formik, and Redux Form.
import { useForm, SubmitHandler } from "react-hook-form"
type Inputs = {
example: string
exampleRequired: string
}
export default function App() {
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useForm<Inputs>()
const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data)
console.log(watch("example")) // watch input value by passing the name of it
return (
/* "handleSubmit" will validate your inputs before invoking "onSubmit" */
<form onSubmit={handleSubmit(onSubmit)}>
{/* register your input into the hook by invoking the "register" function */}
<input defaultValue="test" {...register("example")} />
{/* include validation with required or other standard HTML validation rules */}
<input {...register("exampleRequired", { required: true })} />
{/* errors will return when field validation fails */}
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
)
}
2. Formik
Formik is a small group of React components and hooks for building forms in React and React Native. It helps with the three most annoying parts:
- Getting values in and out of form state
- Validation and error messages
- Handling form submission
import React from 'react';
import { useFormik } from 'formik';
const SignupForm = () => {
// Pass the useFormik() hook initial form values and a submit function that will
// be called when the form is submitted
const formik = useFormik({
initialValues: {
email: '',
},
onSubmit: values => {
alert(JSON.stringify(values, null, 2));
},
});
return (
<form onSubmit={formik.handleSubmit}>
<label htmlFor="email">Email Address</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
<button type="submit">Submit</button>
</form>
);
};
3. React Final Form
React Final Form is a thin React wrapper for Final Form, which is a subscriptions-based form state management library that uses the Observer pattern, so only the components that need updating are re-rendered as the form's state changes.
For small forms, redrawing your entire form on every keypress is no problem. But when your form grows, performance can degrade.
Final Form is a high performance subscription-based form state management solution for React. It is designed to be modular, zero dependencies, and hooks compatible.
import { Form, Field } from 'react-final-form'
const MyForm = () => (
<Form
onSubmit={onSubmit}
validate={validate}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<h2>Simple Default Input</h2>
<div>
<label>First Name</label>
<Field name="firstName" component="input" placeholder="First Name" />
</div>
<h2>An Arbitrary Reusable Input Component</h2>
<div>
<label>Interests</label>
<Field name="interests" component={InterestPicker} />
</div>
<h2>Render Function</h2>
<Field
name="bio"
render={({ input, meta }) => (
<div>
<label>Bio</label>
<textarea {...input} />
{meta.touched && meta.error && <span>{meta.error}</span>}
</div>
)}
/>
<h2>Render Function as Children</h2>
<Field name="phone">
{({ input, meta }) => (
<div>
<label>Phone</label>
<input type="text" {...input} placeholder="Phone" />
{meta.touched && meta.error && <span>{meta.error}</span>}
</div>
)}
</Field>
<button type="submit">Submit</button>
</form>
)}
/>
)
4. @formily/core
Formily is an innovative toolkit designed to streamline the creation of dynamic forms while ensuring optimal performance across various devices.
Features
πΌ Designable, You can quickly develop forms at low cost through Form Builder.
π High performance, fields managed independently, rather rerender the whole tree.
π‘ Integrated Alibaba Fusion and Ant Design components are guaranteed to work out of the box.
π¨ JSON Schema applied for BackEnd. JSchema applied for FrontEnd. Two paradigms can be converted to each other.
π Side effects are managed independently, making form data linkages easier than ever before.
π― Override most complicated form layout use cases.
import React from 'react'
import { createForm } from '@formily/core'
import { FormProvider, FormConsumer, Field } from '@formily/react'
import {
FormItem,
FormLayout,
Input,
FormButtonGroup,
Submit,
} from '@formily/antd'
const form = createForm()
export default () => {
return (
<FormProvider form={form}>
<FormLayout layout="vertical">
<Field
name="input"
title="Input box"
required
initialValue="Hello world"
decorator={[FormItem]}
component={[Input]}
/>
</FormLayout>
<FormConsumer>
{() => (
<div
style={{
marginBottom: 20,
padding: 5,
border: '1px dashed #666',
}}
>
Real-time responseοΌ{form.values.input}
</div>
)}
</FormConsumer>
<FormButtonGroup>
<Submit onSubmit={console.log}>submit</Submit>
</FormButtonGroup>
</FormProvider>
)
}
Top comments (0)