Reorder animation on FlatList items using itemLayoutAnimation prop #6322
-
Hi, I'm having trouble creating the FlatList animation described here https://docs.swmansion.com/react-native-reanimated/docs/layout-animations/list-layout-animations. How to do it correctly so that there is an animation when “Reorder” button is pressed? Am I missing something here? If so, it's described a bit poorly on the site. import Animated, { LinearTransition } from 'react-native-reanimated';
const transition = LinearTransition.springify().duration(500);
export function Screen() {
const insets = useSafeAreaInsets();
const [tasks, setTasks] = useState(['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5']);
function reorderTasks() {
setTasks((prevTasks) => [...prevTasks.reverse()]);
}
function addTask() {
setTasks((prevTasks) => [...prevTasks, `Task ${prev.length + 1}`]);
}
function removeTask() {
setTasks((prevTasks) => [...prevTasks.slice(0, prevTasks.length - 1)]);
}
const renderTask = useCallback(({ item }: ListRenderItemInfo<string>) => {
return (
<View
style={{
backgroundColor: 'green',
height: 70,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>{item}</Text>
</View>
);
}, []);
return (
<View style={[styles.wrapper, { paddingTop: insets.top }]}>
<Animated.FlatList
contentContainerStyle={styles.listContentWrapper}
data={tasks}
renderItem={renderTask}
itemLayoutAnimation={transition}
/>
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
<Button title="Reorder" onPress={reorderTasks} />
<Button title="Add" onPress={addTask} />
<Button title="Remove" onPress={removeTask} />
</View>
</View>
);
} Screen.Recording.2024-07-23.at.19.01.00.mov |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey! keyExtractor={(item) => item} |
Beta Was this translation helpful? Give feedback.
Hey!
Thank you for noticing the issue. It turns out that you need to add the
keyExtractor
property to yourAnimated.FlatList
if your list items have neither theid
nor thekey
property.In general, the default
keyExtractor
in react native looks for only these 2 properties in your list items. If neither of these exists, you should provide your own implementation for efficient list items updated. It looks likeitemLayoutAnimation
also needs to know item keys. In your case, the following implementation ofkeyExtractor
will fix the issue: