React hook form default values


React Hook Form provides many other features for form validation, custom validations, error handling, and more. You can explore the official documentation for more information on how to use React Hook Form effectively: https://react-hook-form.com/

install the react-hook-form library using a package manager like npm or yarn before using it in your project:

npm install react-hook-form
# or
yarn add react-hook-form

In React Hook Form, you can set default values for your form inputs using the defaultValue or defaultValues prop. Here’s an example of using default values with React Hook Form:

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

const MyForm = () => {
  const { register, handleSubmit } = useForm({
    defaultValues: {
      firstName: 'John',
      lastName: 'Doe',
      email: '',
    },
  });

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>
        First Name:
        <input type="text" {...register('firstName')} />
      </label>
      <label>
        Last Name:
        <input type="text" {...register('lastName')} />
      </label>
      <label>
        Email:
        <input type="email" {...register('email')} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
};

In this example, we use the defaultValues property when calling useForm to set the initial values for the form inputs. The defaultValues object contains the default values for each input field. In this case, the firstName and lastName fields are pre-filled with default values, while the email field is left empty.

By passing the defaultValues object to useForm, the specified default values will be applied to the corresponding input fields when the form is rendered.

You can customize the default values according to your needs. If you want to set default values dynamically based on some data or fetched from an API, you can make an asynchronous call and then set the default values once the data is available.