Jalan Technologies > Blog >

Top Form Handling Libraries In React

Explore the top React form handling libraries: Formik, known for simplicity and a large community; React Final Form, leveraging an observable design pattern for speed; and React Hook Form, a flexible and lightweight option with built-in validation. Choose the right library based on your project's specific needs and streamline form development.

Forms are an essential part of almost every website. In React, form handling has seen a lot of phases.

Things used to be complex at first especially for longer forms but now, there are countless libraries that are used to create, manage and handle the state of forms in React.

When it comes to choosing a library, it is not an easy task, this is why we have compiled a list of ——-

Top Form Handling Libraries In React.

So let’s get started.

Formik

Formik has been the most popular library for form management in React. As of now, it has more than 27.5k stars on GitHub with a million weekly downloads.

With this much popularity, Formik has a huge community and you will get answers to most of your answers regarding it. You can install Formik with the following command in your React project.

npm i formik

Creating forms in Formik is really simple. It provides you with Form and Field component that are resided inside Formik component; the main wrapper for the form. The following code snippet will create a simple form in your app.

import React from 'react';
import ReactDOM from 'react-dom';
import { Formik, Field, Form } from 'formik';

const Basic = () => (
  <div>
    <h1>Sign Up</h1>
    <Formik
      initialValues={{
        firstName: '',
        lastName: '',
        email: '',
      }}
      onSubmit={async (values) => {
        await new Promise((r) => setTimeout(r, 500));
        alert(JSON.stringify(values, null, 2));
      }}
    >
      <Form>
        <label htmlFor="firstName">First Name</label>
        <Field id="firstName" name="firstName" placeholder="First Name" />

        <label htmlFor="lastName">Last Name</label>
        <Field id="lastName" name="lastName" placeholder="Last Name" />

        <label htmlFor="email">Email</label>
        <Field
          id="email"
          name="email"
          placeholder="Email"
          type="email"
        />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  </div>
);

ReactDOM.render(<Basic />, document.getElementById('root'));

React Final Form

React final form is another amazing library for form handling in React. It is a wrapper around the final form which is a lightweight, dependency-free form management library written in core Javascript.

React final form follows an observable design patterns for managing the state of the form. It uses subscription that only updates the components that are required instead of updating the whole form.

This makes React Final Form really fast for forms with more than 200 fields. The use of this library is quite similar to Formik. It does not provide any validation mechanism and for that purpose, you have to use libraries like Yup.

We can install React Final Form with the following command.

npm i react-final-form

The following code will create a simple form with subscriptions enabled.

import React from 'react'
import { render } from 'react-dom'
import Styles from './Styles'
import { Form, Field, FormSpy } from 'react-final-form'
import RenderCount from './RenderCount'

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

const onSubmit = async values => {
  await sleep(300)
  window.alert(JSON.stringify(values, 0, 2))
}
const required = value => (value ? undefined : 'Required')

const App = () => (
  <div>
    <MyForm subscription={{ submitting: true, pristine: true }} />
  </div>
)

const MyForm = ({ subscription }) => (
  <Form
    onSubmit={onSubmit}
    subscription={subscription}
    render={({ handleSubmit, form, submitting, pristine, values }) => (
      <form onSubmit={handleSubmit}>
      
        <Field name="firstName" validate={required}>
          {({ input, meta }) => (
            <div>
              <label>First Name</label>
              <input {...input} placeholder="First Name" />
              {meta.touched && meta.error && <span>{meta.error}</span>}
            </div>
          )}
        </Field>
        <Field name="lastName" validate={required}>
          {({ input, meta }) => (
            <div>
              <label>Last Name</label>
              <input {...input} placeholder="Last Name" />
              {meta.touched && meta.error && <span>{meta.error}</span>}
            </div>
          )}
        </Field>
        <div className="buttons">
          <button type="submit" disabled={submitting}>
            Submit
          </button>
          <button
            type="button"
            onClick={form.reset}
            disabled={submitting || pristine}
          >
            Reset
          </button>
        </div>
        
      </form>
    )}
  />
)

render(<App />, document.getElementById('root'))

React Hook Form

React Hook Form is one of the most flexible libraries when it comes to creating forms. It has an inbuilt validation mechanism that makes it really powerful. It is a small package without any dependencies.

It uses a single hook to do most of the required stuff. The main feature of React hook forms is that it prevents unnecessary re-renders while updating the form.

We can install it with the following command.

npm i react-hook-form

The code for a sample form is given below

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => {
    console.log(data);
  }; // your form submit function which will invoke after successful validation


  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>First Name</label>
      <input name="First" defaultValue="test" ref={register} />
      <label>Last Name</label>
      <input
        name="exampleRequired"
        ref={register({ required: true, maxLength: 10 })}
      />
      {errors.exampleRequired && <p>This field is required</p>}
      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The validation is checked when the form is submitted.

Conclusion

In this article, we have seen top form handling libraries in React. Before choosing one, you should always make sure that the selected library fulfils your project requirements.

What’s the biggest thing you’re struggling with right now that we as a technology consulting company can help you with? Feel free to reach out to us at info@jalantechnologies.com. We hope our assistance will help!

Disclaimer: The statements and opinions expressed in this article are those of the author(s) and do not necessarily reflect the positions of Jalan Technologies.

Table of Contents

Hire Our Development Experts.




    Want to raise the bar for your organization?

    Subscribe to our newsletter to receive latest insights on how technology can help turn your goals into reality. By subscribing, you’ll get access to thought-provoking articles, case studies, and resources to help accelerate your impact.

    Get the latest updates straight to your inbox

      Related Blogs
      technology consultant
      Business Insights
      All you need to know about technology consultant

      Technology consultant experts like Jalan Technologies, empowers businesses to strategically leverage technology for success. Services encompass strategic planning, system integration,

      Scroll to Top

      Subscribe Now

        Never Miss Another Post