diff --git a/packages/ra-core/src/form/FormDataConsumer.spec.tsx b/packages/ra-core/src/form/FormDataConsumer.spec.tsx
index 6498b370990..a45fc7acc88 100644
--- a/packages/ra-core/src/form/FormDataConsumer.spec.tsx
+++ b/packages/ra-core/src/form/FormDataConsumer.spec.tsx
@@ -140,4 +140,78 @@ describe('FormDataConsumerView', () => {
});
});
});
+
+ it('calls its children with the index when inside an ArrayInput', async () => {
+ let globalIndex;
+
+ render(
+
+
+
+
+
+
+ {({ index }) => {
+ globalIndex = index;
+ return null;
+ }}
+
+
+
+
+
+
+ );
+
+ expect(globalIndex).toEqual(undefined);
+
+ fireEvent.click(screen.getByLabelText('ra.action.add'));
+
+ expect(globalIndex).toEqual(0);
+
+ fireEvent.click(screen.getByLabelText('ra.action.add'));
+
+ expect(globalIndex).toEqual(1);
+ });
+
+ it('calls its children with the correct index when inside nested ArrayInputs', async () => {
+ let innerIndex: number | undefined;
+
+ render(
+
+
+
+
+
+
+
+
+ {({ index }) => {
+ innerIndex = index;
+ return null;
+ }}
+
+
+
+
+
+
+
+
+ );
+
+ await waitFor(() => {
+ // The inner array's first item should have index 0,
+ // not the outer array's index (also 0 in this case)
+ expect(innerIndex).toEqual(0);
+ });
+ });
});
diff --git a/packages/ra-core/src/form/FormDataConsumer.tsx b/packages/ra-core/src/form/FormDataConsumer.tsx
index f0f4176ec1e..215d0da6616 100644
--- a/packages/ra-core/src/form/FormDataConsumer.tsx
+++ b/packages/ra-core/src/form/FormDataConsumer.tsx
@@ -77,7 +77,9 @@ export const FormDataConsumerView = <
// If we have an index, we are in an iterator like component (such as the SimpleFormIterator)
if (arraySource) {
const scopedFormData = get(formData, arraySource);
- result = children({ formData, scopedFormData });
+ const matches = [...arraySource.matchAll(/\d+/g)];
+ const index = Number(matches[matches.length - 1]?.[0]);
+ result = children({ formData, scopedFormData, index });
} else {
result = children({ formData });
}
@@ -98,6 +100,7 @@ export interface FormDataConsumerRenderParams<
> {
formData: TFieldValues;
scopedFormData?: TScopedFieldValues;
+ index?: number;
}
export type FormDataConsumerRender<