Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create an onClick event with React Hook Form using 'append', follow the steps below:

Step 1: Import the required modules

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

Step 2: Create the function to handle the onClick event

const onClickHandler = () => {
  append({ name: "example" });
};

Step 3: Initialize the react-hook-form

const { register, handleSubmit, errors, append } = useForm();

Step 4: Create the form

<form onSubmit={handleSubmit(onSubmit)}>
  <input type="submit" />
  <button onClick={onClickHandler}>Add Input</button>
  {errors.example && <p>{errors.example.message}</p>}
</form>

Here, the onClick event is handled by the onClickHandler function, and the 'append' function is called to add another input field to the form with the name 'example'.