i have a component that has fields props and this each prop map render in Formik.
But react throw an error.
React throw an error like this :
Warning: Each child in a list should have a unique "key" prop.
Check the render method of FieldArrayInner. See https://reactjs.org/link/warning-keys for more information.
My code below –>
<Formik
initialValues={initialValues}
onSubmit={onSubmit}
validate={validate}
>
{({ values, handleSubmit, handleChange, errors }: formikProps) => (
<form
onSubmit={handleSubmit}
className={`space-y-4 sm:space-y-0 ${
formType === "login"
? ""
: "sm:grid sm:grid-cols-2 sm:grid-rows-[auto_auto_auto_auto_auto_40px]"
} flex flex-col gap-4`}
>
<FieldArray
name="fields"
render={() => (
<>
{fields.map((field, index) => (
// I puted id here
<div key={index}>
<label
htmlFor={field.name}
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
{field.label}
</label>
{field.options && (
<select
name={field.name}
value={values[field.name]}
onChange={handleChange}
className="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
data-testid={`${field.name}-input`}
>
{field.options.map((option) => (
<option value={option.value}>
{option.label}
</option>
))}
</select>
)}
{!field.options && (
<input
type={field.type}
name={field.name}
value={values[field.name]}
onChange={handleChange}
placeholder={field.placeholder}
className="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
data-testid={`${field.name}-input`}
/>
)}
{errors[field.name] && (
<div className="text-red-500 text-xs italic">
{errors[field.name]}
</div>
)}
</div>
))}
</>
)}
/>
<Button type="submit" className="w-full col-span-2">
{submitLabel}
</Button>
<span className="text-xs text-gray-500 dark:text-gray-400">
{message}
</span>
</form>
)}
</Formik>
interface FormProps {
...
fields: {
name: string;
label: string;
type?: string;
placeholder?: string;
options?: { value: string; label: string }[];
}[];
...
}
Thank you for informations.
>Solution :
This is related to field.options.map, each item that are being mapped must have a unique key
so simply add it like this :
{field.options.map((option,index) => (
<option key={index} value={option.value}>
{option.label}
</option>
))}