Skip to content

Commit ba6a5ae

Browse files
authored
Merge pull request #7404 from alanpoulain/fix/simple-form-iterator-transition-index
fix: use right index for the transition in SimpleFormIterator
2 parents 0cbf4fe + d54bb69 commit ba6a5ae

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

packages/ra-ui-materialui/src/input/ArrayInput/SimpleFormIterator.tsx

+25-1
Original file line numberDiff line numberDiff line change
@@ -44,20 +44,41 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
4444
disableRemove,
4545
disableReordering,
4646
TransitionProps,
47+
defaultValue,
4748
getItemLabel = DefaultLabelFn,
4849
} = props;
4950
const { append, fields, move, remove } = useArrayInput(props);
5051
const nodeRef = useRef();
5152

53+
// We need a unique id for each field for a proper enter/exit animation
54+
// so we keep an internal map between the field position and an auto-increment id
55+
const nextId = useRef(
56+
fields && fields.length
57+
? fields.length
58+
: defaultValue
59+
? defaultValue.length
60+
: 0
61+
);
62+
63+
// We check whether we have a defaultValue (which must be an array) before checking
64+
// the fields prop which will always be empty for a new record.
65+
// Without it, our ids wouldn't match the default value and we would get key warnings
66+
// on the CssTransition element inside our render method
67+
const ids = useRef(
68+
nextId.current > 0 ? Array.from(Array(nextId.current).keys()) : []
69+
);
70+
5271
const removeField = useCallback(
5372
(index: number) => {
73+
ids.current.splice(index, 1);
5474
remove(index);
5575
},
5676
[remove]
5777
);
5878

5979
const addField = useCallback(
6080
(item: any = undefined) => {
81+
ids.current.push(nextId.current++);
6182
append(item);
6283
},
6384
[append]
@@ -75,6 +96,9 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
7596

7697
const handleReorder = useCallback(
7798
(origin: number, destination: number) => {
99+
const item = ids.current[origin];
100+
ids.current[origin] = ids.current[destination];
101+
ids.current[destination] = item;
78102
move(origin, destination);
79103
},
80104
[move]
@@ -98,7 +122,7 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
98122
{fields.map((member, index) => (
99123
<CSSTransition
100124
nodeRef={nodeRef}
101-
key={member.id}
125+
key={ids.current[index]}
102126
timeout={500}
103127
classNames="fade"
104128
{...TransitionProps}

0 commit comments

Comments
 (0)