DEV Community

Cover image for Reusable React Hook Form
NISHARGA KABIR
NISHARGA KABIR

Posted on

Reusable React Hook Form

We will use typescript with nextjs but you can use it as your wish funda is same as this ☺️☺️☺️

Install: npm install react-hook-form

Step 1: Create a Form.tsx file

import { useForm, FormProvider, SubmitHandler } from 'react-hook-form';
import React from 'react';

interface FormProps {
    children: React.ReactNode;
    defaultValues?: Record<string, any>;
    submitHandler: SubmitHandler<Record<string, any>>;
}

const Form = ({ children, defaultValues, submitHandler }: FormProps) => {
    const methods = useForm({ defaultValues });
    const { handleSubmit, reset } = methods;

    const onSubmit: SubmitHandler<Record<string, any>> = (data) => {
        submitHandler(data);
        reset(defaultValues); // Reset to default values after submit
    };

    return (
        <FormProvider {...methods}>
            <form onSubmit={handleSubmit(onSubmit)}>{children}</form>
        </FormProvider>
    );
};

export default Form;
Enter fullscreen mode Exit fullscreen mode

Heres we do nothing. Just do copy peast from react hook form doc. 😅

We needs 3 things as perameter. Default value, submit handler and children….

  • Default value is used for user experience. We can reset it after form submits or we can handle it in our way.
  • Submit handler is the same thing you use in html… e.target.value do you forget it? It's the same.
  • And children no need to describe whatever you pass it it will take it.

FormProps is typescript declare you can ignore it. Now start the main agenda.

In the method variable, we take useForm which is the preBuild function for reactHookForm and as input, we pass our default value. Finally calling it into our formProvider.

Then handleSubmit and reset we destrure from methods. onSubmit Function

Form > form onSubmit > We use that handleSubmit function

And inside the onSubmit function we use reset….

And last one thing submitHandler came from reactHookForm

Inside the return function, we use the same convention as reactHookForm suggests us…… Our 60% job done. Now move to step 2;

Step 2: Create a FormInput.tsx file

import { Controller, useFormContext } from 'react-hook-form';

interface FormInputProps {
    name: string;
    type: string;
    placeholder?: string;
}

const FormInput = ({ name, type, placeholder }: FormInputProps) => {
    const { control } = useFormContext();
    return (
        <Controller
            control={control}
            name={name}
            render={({ field }) => (
                <input type={type} placeholder={placeholder} {...field} />
            )}
        />
    );
};

export default FormInput;
Enter fullscreen mode Exit fullscreen mode

Basically, we are working here only name, type, and placeholder. If you want you can work with lots of things it depends on which CSS framework you use. We are using nothing.

We mainly need a controller component that came from reactHookForm.

Which expect three things.

  1. control
  2. name
  3. render
  • Control is came from useFromContect Hook which is a preBuild thing for reactHookForm. No need to create it.
  • The name is same thing as we use in html input..
  • Using render method we will got field. Whatever things we pass into our inputs it will take it. As example in our form we pass size=”lg” so it will set here.

Our 95% work done. Now its time to use it. 😍😍

Step 3: create a file or in the app.ts / app.js file

before return peast this

const onSubmit = (data: Record<string, any>) => {
console.log(data);
};

this is nothing to describe in HTML lots of times you use it.

and
inside return

<Form submitHandler={onSubmit} defaultValues={{ name: '' }}>
<FormInput type='text' name='name' placeholder='Name' />
<input type='submit' value='send' />
</Form>

Form and FormInput in our created Step1 and Step2 file. submitHandler came from reactHookForm and defaultValue whatever you wants you can pass. just remember its just a pattern of name field.

live looks like this

It will looks like this and after form submit we will got our values 😍😍😍

Top comments (0)