Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 14, 2021 02:45 am GMT

Building Forms with useForm

One of the most important steps when you are developing web applications is how to write and maintain smart forms with little effort.
When you think about reactjs you can find many options of form library and I must admit that has a lot of good form libraries, and you can think why one more?

UseForm was born because I feel great difficulty when I needed to build complex forms with many fields in different steps or level.

When we need to build complex forms we can bump in some points like:

  • A lot of rendering - Every change that happened in the form state is reflected and the form component tree is rendered again and again.

  • A lot of properties - When you use some libraries is necessary to put many properties in one input, creating a lot of unnecessary code.

  • Just one approach - You can use controlled forms or uncontrolled forms never both together.

  • Share state - You should share the form state with many other components like a step form and a form library should provide it.

How useForm works

The most important thing to say it has three ways to use it:

  • You can build an uncontrolled form, this is the most performative form because the input value is not saved in the component state and all changes are realized with a component reference and native events. It means you can fill out a form and submit it with just one render.

  • You can build a controlled form, definitely this is not the most performative way to build a form, but this is the way the user can feel a better experience, it's so frustrating when you fill a form and just after you submit it for you realize that some fields value are wrong. When you use a controlled form you can show the user if some values are wrong and the user can fix with the right value and go on.

  • You can use the debounce approach, in my opinion, this is the better options because you can have the best of both worlds(Jean-Luc Picard). This is a good explanation about this: The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called.

If you are interested in this library leave a star on this : https://github.com/use-form/use-form

Show me the code

Build a simple form.

In our first example let me show you how we can build a simple form and how you can define if will be a controlled, uncontrolled or debounce form.

import { useForm } from "@use-form/use-form";const initialValues = {  name: 'Jesse',  email: '[email protected]',  score: 25,}const { register, state: { values }} = useForm({initialValues})<Input placeholder="Name" {...register("name")}/><Input placeholder="E-mail" type="email"{...register("email")}/><Range {...register("score")}/>
Enter fullscreen mode Exit fullscreen mode

useForm can receives many properties and some of these properties are: isDebounced and isControlled.

By default, useForm use uncontrolled approach.

Adding validation with yup

When we are working with real application validations forms are very common because this is the way you can verify if the input's value is correct or not. There are several validations solutions available, but when using useForm the default solution is Yup. With yup the process of validations is simple and powerful.

import { useForm } from "@use-form/use-form";import * as yup from "yup";const initialValues = {  name: "Jesse",  email: "[email protected]",  pets: ["felix"],  accept: false,};const validation = yup.object().shape({  name: yup.string().required("This field is required"),  email: yup    .string()    .email("This field must be a valid e-mail")    .required("This field is required"),  pets: yup.array(yup.string().required("This field is required")),  accept: yup.bool().oneOf([true], "Field must be checked"),});function ControlledForm() {  const { register, state } = useForm({    isControlled: true,    initialValues,    validationSchema,  });  return (    <>      <input {...register("name")} />      <span>{touched.name && errors.name}</span>      <input type="email" {...register("email")} />      <span>{touched.email && errors.email}</span>      <input {...register("pets.0")} />      <span>{touched.pets?.[0] && errors.pets?.[0]}</span>      <input type="checkbox" {...register("accept")} />      <span>{touched.accept && errors.accept}</span>    </>  );}
Enter fullscreen mode Exit fullscreen mode

FormContext

FormContext provides a way to share a form state with another component in the tree.

const form = useForm(...)<ContextForm.Provider value={form}> {/* ....another components */}</ContextForm.Provider>
Enter fullscreen mode Exit fullscreen mode

and

const {register, ...form} = useFormContext()<Input placeholder="Name" {register('otherPerson.name')}/>
Enter fullscreen mode Exit fullscreen mode

UseForm has a lot of resources, and you can look at this on this link. https://useform.org

Conclusion

I hope you have enjoyed this post and have found it helpful, useForm is a new library to build forms and have small documentation in English, if you want to start with open source this repository can be your first step.

https://github.com/use-form/use-form


Original Link: https://dev.to/jucian0/building-forms-with-useform-1cna

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To