Fix array form field removing items in the middle bugging out
Some checks failed
E2E Tests / e2e (push) Has been cancelled
Tests and checks on push / run-checks-and-tests (push) Has been cancelled
Updates translation progress / update-translation-progress-issue (push) Has been cancelled

Should not use "idx" as a key like that. React gets confused.
This commit is contained in:
Kalle
2026-02-26 20:17:01 +02:00
parent e6d0a8189f
commit eb949bb5de
3 changed files with 118 additions and 5 deletions

View File

@@ -39,12 +39,19 @@ export function ArrayFormField({
const count = value.length;
const handleAdd = () => {
const newItemValue =
const baseValue =
itemInitialValue !== undefined
? itemInitialValue
: isObjectArray
? {}
: undefined;
const newItemValue =
typeof baseValue === "object" && baseValue !== null
? {
...(baseValue as Record<string, unknown>),
_key: crypto.randomUUID(),
}
: baseValue;
onChange([...value, newItemValue]);
};
@@ -52,6 +59,11 @@ export function ArrayFormField({
onChange(value.filter((_, i) => i !== index));
};
const itemKey = (idx: number) => {
if (!isObjectArray) return idx;
return ((value[idx] as Record<string, unknown>)?._key as string) ?? idx;
};
return (
<div className="stack md w-full">
{translatedLabel ? (
@@ -60,7 +72,7 @@ export function ArrayFormField({
{Array.from({ length: count }).map((_, idx) =>
isObjectArray ? (
<ArrayItemFieldset
key={idx}
key={itemKey(idx)}
index={idx}
canRemove={count > min}
onRemove={() => handleRemoveAt(idx)}
@@ -69,7 +81,10 @@ export function ArrayFormField({
{renderItem(idx, `${name}[${idx}]`)}
</ArrayItemFieldset>
) : (
<div key={idx} className="stack horizontal sm items-center w-full">
<div
key={itemKey(idx)}
className="stack horizontal sm items-center w-full"
>
<div className={styles.itemInput}>
{renderItem(idx, `${name}[${idx}]`)}
</div>