4

I'm using React Hook Form library. https://react-hook-form.com

If it's a simple form like Student Name, and Student Age, the application is quite simple.

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

I just create those two input fields and register them.

               <div className="w-full flex flex-col mt-4">
                  <label>Name</label>
                  <input
                    type="text"
                    placeholder="Enter Name" {...register("name")}
                  />

                </div>
                <div className="w-full flex flex-col mt-4">
                  <label>Age</label>
                  <input
                    type="text"
                    placeholder="Enter Age" {...register("age")}
                  />

                </div>
                <div>
                  <button onClick={handleSubmit(submitData)}>
                    Update
                  </button>
                </div>

The submitData function will get the formData which can be used. The handleSubmit binds the registered fields to formData

const submitData = async formData => {
  console.log(formData)
}

The formData will look as below:

{"name":"test", "age":"27"}

My requirement is to make this form dynamic, by allowing me to add many students. I should be able to repeat a set of these fields with a button called "Add Student". Every time I add a new student, it should create a new row of these two fields where I can add new students names. finally, the output of the formData should look like an array of students:

[{"name":"test1", "age":27},{"name":"test2", "age":28},{"name":"test3", "age":29} ]

I can create the UI to add the new fields, but I don't know how to bind them to the formData in react hook form. In the documentation, I couldn't find how to do this with react hook form.

Please help.

3
  • Can you please provide your full code, including usage of the useForm hook? Commented Apr 28, 2021 at 4:28
  • There isn't much other than what I've provided above. The useForm usage is: const { register, handleSubmit, formState: { errors } } = useForm(); And from this register is used to register fields, which is shown above. Commented Apr 28, 2021 at 4:46
  • 3
    Here is a whole video on the process: youtu.be/61AlrA5BXzg, here is the sample from react-hook-form: codesandbox.io/s/react-hook-form-usefieldarray-ssugn Commented Apr 29, 2021 at 2:45

1 Answer 1

5

I tried the following:

I created a state as follows:

const [items, setItems] = useState([0,1,2])

I can update this when I add/remove items.

Now, for the fields, I wrapped them into a map as follows:

{items.map(i => (
    <div>
        <div className="w-full flex flex-col mt-4">
            <label>Name</label>
            <input
            type="text"
            placeholder="Enter Name" {...register(`items[${i}].name`)}
            />

        </div>
        <div className="w-full flex flex-col mt-4">
            <label>Age</label>
            <input
            type="text"
            placeholder="Enter Age" {...register(`items[${i}].age`)}
            />

        </div>
    </div>
))}

This works.

Sign up to request clarification or add additional context in comments.

6 Comments

Oh man, you just broke my heart, I was working on this for you. Lol
But how did you handle the dynamic keys for each form data value when handleSubmit is called?
Oh, you can still add your answer.
The form data now returns an array {"items": [{"name":"ss", "age","27"},{"name":"ff", "age","27"},{"name":"ff", "age","27"}]}}
Ok, well I just posted what I was doing, I wasn't done with it so it's not working as expected but hopefully, it should give you more ideas. @asanas
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.