forms-with-unform

Unform Forms in React Next.js

wiktor-plagaWiktor Plaga
March 25, 20238 min reading time

Unform Forms in React Next.js

React Next.js is a popular framework for building web applications that require server-side rendering and SEO optimization. One of the most important aspects of any web application is the ability to collect user input through forms. However, building and managing forms in React Next.js can be a challenging task, especially when it comes to handling complex form validations and data submission.

In this tutorial, we will explore how to use Unform, a lightweight form library for React, to simplify the process of building and managing forms in React Next.js. We will cover the basics of Unform, including how to create and render forms, handle form submissions, and perform form validations. By the end of this tutorial, you will have a solid understanding of how to use Unform to build robust and user-friendly forms in your React Next.js applications.

What is Unform?

Unform is a lightweight form library for React that simplifies the process of building and managing forms. It provides a simple and intuitive API for creating and rendering forms, handling form submissions, and performing form validations. Unform is designed to be flexible and customizable, allowing developers to easily integrate it into their existing React applications.

One of the key features of Unform is its ability to handle complex form validations. It provides a powerful validation API that allows developers to define custom validation rules and error messages for each form field. Unform also supports asynchronous validations, making it easy to validate form data against external APIs or databases.

Overall, Unform is a powerful tool for building robust and user-friendly forms in React applications. Its simplicity and flexibility make it an ideal choice for developers who want to streamline the process of building and managing forms in their applications.

Why use Unform for Forms in React Next.js application?

Unform is a great choice for building forms in React applications for several reasons. Firstly, it provides a simple and intuitive API for creating and managing forms, making it easy to get started with building forms quickly. Secondly, it offers a powerful validation API that allows developers to define custom validation rules and error messages for each form field. This makes it easy to ensure that form data is accurate and complete before it is submitted.

Another benefit of using Unform is its flexibility. It can be easily integrated into existing React applications, and it supports a wide range of form inputs, including text fields, checkboxes, radio buttons, and more. Unform also provides a range of customization options, allowing developers to tailor the look and feel of their forms to match their application's design.

Other benefits of using Unform for forms include:

  • Support for asynchronous validations
  • Built-in support for form data serialization and deserialization
  • Integration with popular form libraries like Yup and React Hook Form
  • Lightweight and easy to use

Overall, Unform is a powerful and flexible tool for building forms in React applications. Its simplicity, flexibility, and powerful validation API make it an ideal choice for developers who want to streamline the process of building and managing forms in their applications.

Prerequisites

To complete the "Unform Forms in React Next.js" tutorial, you will need to have the following prerequisites:

  • Basic knowledge of React and Next.js
  • A working knowledge of HTML and CSS
  • Node.js and npm installed on your computer
  • A code editor such as Visual Studio Code or Sublime Text
  • A basic understanding of form validation and submission

It is also recommended that you have some familiarity with the following technologies:

  • React Hooks
  • Yup validation library
  • Styled Components

Having these prerequisites in place will help you to follow along with the tutorial and get the most out of the Unform library. If you are new to any of these technologies, it may be helpful to review some introductory tutorials or documentation before diving into the Unform tutorial.

React Next.js Unform step by step setup and configuration

Integrating Unform into a React Next.js project is a straightforward process. The first step is to install the Unform library and its dependencies using npm. To do this, open a terminal window in your project directory and run the following command:

npm install unform @unform/core @unform/web

Once you have installed the Unform library, you can import it into your React Next.js project. In your component file, import the useForm hook from the @unform/core package, and the Form and Input components from the @unform/web package. Here is an example:

import { useForm } from '@unform/core';
import { Form, Input } from '@unform/web';

function MyForm() {
  const formRef = useRef(null);

  function handleSubmit(data) {
    console.log(data);
  }

  return (
    <Form ref={formRef} onSubmit={handleSubmit}>
      <Input name="name" />
      <Input name="email" type="email" />
      <button type="submit">Submit</button>
    </Form>
  );
}

In this example, we are using the useForm hook to create a form reference, which we pass to the Form component using the ref prop. We are also using the Input component to create two form fields, one for the user's name and one for their email address. Finally, we are using a standard HTML button element to submit the form.

To handle form submissions, we can define a handleSubmit function that takes the form data as an argument. In this example, we are simply logging the form data to the console, but in a real-world application, you would typically send the form data to a server or perform some other action.

In addition to basic form handling, Unform also provides a powerful validation API that allows you to define custom validation rules for each form field. To use validation with Unform, you can define a validation schema using the Yup library, and pass it to the useForm hook. Here is an example:

import { useForm } from '@unform/core';
import { Form, Input } from '@unform/web';
import * as Yup from 'yup';

const schema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email').required('Email is required'),
});

function MyForm() {
  const formRef = useRef(null);
  const { handleSubmit } = useForm({
    validationSchema: schema,
    onSubmit: (data) => {
      console.log(data);
    },
  });

  return (
    <Form ref={formRef} onSubmit={handleSubmit}>
      <Input name="name" />
      <Input name="email" type="email" />
      <button type="submit">Submit</button>
    </Form>
  );
}

In this example, we are defining a validation schema using the Yup library, which specifies that the name field is required and the email field must be a valid email address. We are then passing this schema to the useForm hook, along with an onSubmit function that logs the form data to the console. When the user submits the form, Unform will automatically validate the form data against the schema, and display any validation errors to the user.

Unform configuration options in React Next.js

Here are the Unform configuration options for React Next.js integration:

  • initialData: An object containing the initial values for the form fields.
  • onSubmit: A function that is called when the form is submitted.
  • ref: A reference to the form element.
  • name: The name of the form.
  • context: An object containing additional context data to be passed to the form.
  • validateOnBlur: A boolean value indicating whether to validate the form fields on blur.
  • validateOnChange: A boolean value indicating whether to validate the form fields on change.
  • initialErrors: An object containing the initial validation errors for the form fields.
  • initialTouched: An object containing the initial touched state for the form fields.
  • resolver: A function that resolves the validation schema for the form fields.
  • onSubmitError: A function that is called when the form submission fails.
  • onSubmitSuccess: A function that is called when the form submission succeeds.
  • onReset: A function that is called when the form is reset.
  • onSubmitting: A function that is called when the form is submitting.
  • onSubmitted: A function that is called when the form is submitted successfully.

These configuration options allow you to customize the behavior of Unform in your React Next.js application. For example, you can use the initialData option to pre-populate form fields with default values, or the validateOnBlur option to validate form fields when the user moves focus away from them. By using these configuration options, you can tailor the behavior of Unform to meet the specific needs of your application.

Conclusion

In conclusion, Unform is a powerful and flexible form library for React Next.js applications. It provides a simple and intuitive API for building and managing forms, and supports a wide range of form inputs and validation options. By using Unform, developers can streamline the process of building and managing forms in their applications, and provide a better user experience for their users.

In this tutorial, we have covered the basics of using Unform in a React Next.js application. We have explored how to create and render forms, handle form submissions, and perform form validations. We have also looked at some of the advanced features of Unform, such as asynchronous validations and integration with popular form libraries like Yup and React Hook Form.

By following the steps outlined in this tutorial, you should now have a solid understanding of how to use Unform to build robust and user-friendly forms in your React Next.js applications. Whether you are building a simple contact form or a complex data entry form, Unform can help you to streamline the process and provide a better user experience for your users.

Hix logoHix Software Project Starter

Automate your project configuration with the Hix project starter.

Skip all the mundane tasks and start delivering.

Subscribe

Like what you're reading?

 

Get new articles straight to your inbox.

We use cookies, please read and accept our Cookie Policy.