@@ -44,20 +44,41 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
44
44
disableRemove,
45
45
disableReordering,
46
46
TransitionProps,
47
+ defaultValue,
47
48
getItemLabel = DefaultLabelFn ,
48
49
} = props ;
49
50
const { append, fields, move, remove } = useArrayInput ( props ) ;
50
51
const nodeRef = useRef ( ) ;
51
52
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
+
52
71
const removeField = useCallback (
53
72
( index : number ) => {
73
+ ids . current . splice ( index , 1 ) ;
54
74
remove ( index ) ;
55
75
} ,
56
76
[ remove ]
57
77
) ;
58
78
59
79
const addField = useCallback (
60
80
( item : any = undefined ) => {
81
+ ids . current . push ( nextId . current ++ ) ;
61
82
append ( item ) ;
62
83
} ,
63
84
[ append ]
@@ -75,6 +96,9 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
75
96
76
97
const handleReorder = useCallback (
77
98
( origin : number , destination : number ) => {
99
+ const item = ids . current [ origin ] ;
100
+ ids . current [ origin ] = ids . current [ destination ] ;
101
+ ids . current [ destination ] = item ;
78
102
move ( origin , destination ) ;
79
103
} ,
80
104
[ move ]
@@ -98,7 +122,7 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
98
122
{ fields . map ( ( member , index ) => (
99
123
< CSSTransition
100
124
nodeRef = { nodeRef }
101
- key = { member . id }
125
+ key = { ids . current [ index ] }
102
126
timeout = { 500 }
103
127
classNames = "fade"
104
128
{ ...TransitionProps }
0 commit comments