Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
How to validate an array with react hook form?

I am rendering a form based on what fields are available in selectedAddress. The key variables are all unique but I am seeing a each child in a list must have a unique key error, and the validation is not working. What am I missing?

import { useForm } from "react-hook-form";

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

const RenderSelectedAddress = () => {
if (selectedAddress && !editAutocompletedForm) {

  const entries = Object.entries(selectedAddress);

  const formEntries = entries.map(([key, value]) => (
    <>
      <label htmlFor={key}>{key}</label>
      <input
        defaultValue={value}
        type="text"
        placeholder="Placeholder"
        id={key}
        {...register( key , { required: "required" })}
      ></input>
      {errors.key && <p>{errors.key.message}</p>}
    </>
  ));

  return formEntries;

}

return null;

};
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Every time you do a map, you need to attribute a key attribute with a unique value to what is being rendered. In this case, you should use divs instead of React.Fragment and give it a key...

const formEntries = entries.map(([key, value]) => (
    <div key={value}>
      <label htmlFor={key}>{key}</label>
      <input
        defaultValue={value}
        type="text"
        placeholder="Placeholder"
        id={key}
        {...register( key , { required: "required" })}
      ></input>
      {errors.key && <p>{errors.key.message}</p>}
    </div>
  ));

this is not mandatory, and you get those warnings, but it's very important for React to optimize rendering. Also, the value of key should be a string, not an object.

Please read the docs, pertaining this subject: https://reactjs.org/docs/lists-and-keys.html

about 4 years ago · Juan Pablo Isaza Report

0

  1. key prop should be on the first child of the rendered list. In your case, you used a fragment which doesn't accept a key prop in the shortened form. Instead of <>...</> use: <React.Fragment key={key}></React.Fragment>.

  2. For the validation error, I beilieve it's the fact that you access the errors incorrectly. Instead of errors.key, use errors[key].

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!