The Problem
Recently I came across an interesting challenge to implement list reorder animation in react native. The idea was not to add more dependencies to the app, but find a lightweight solution to animate reordering of items in the FlatList.
The Solution
One interesting API that I found is LayoutAnimation, which is available out of the box in react native. The usage is quite simple. Before setting the new state, call LayoutAnimation.configureNext with the animation configuration. Then set the new list in the state. React native will update the state with the animation!
LayoutAnimation.configureNext({
duration: 200,
create: { type: "linear", property: "opacity" },
update: { type: "linear", property: "opacity" },
delete: { type: "linear", property: "opacity" },
});
setItems(newItems);
Below is a working example for demonstration. It randomly shuffles the list items and update the list with animation.
https://snack.expo.dev/-dHddw3mOPBNXqi37iatm
The animation works smoothly on both iOS and Android. However, to enable this feature on Android, a call to UIManager.setLayoutAnimationEnabledExperimental is required, otherwise the animation will not work.
if (
Platform.OS === "android" &&
UIManager.setLayoutAnimationEnabledExperimental
) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
Animation Configuration
The config parameter is an object with the keys below.
- duration in milliseconds
- create, optional config for animating in new views
- update, optional config for animating views that have been updated
- delete, optional config for animating views as they are removed
The config that's passed to create, update, or delete has the following keys:
- type
- property
- springDamping
- initialVelocity
- delay
- duration
The full list of possible types, properties and presets is available in the official react native documentation.
Pitfalls
The API need to compare before vs after list items to figure out which ones are added/deleted/updated. Implementing keyExtractor for the FlatList correctly is important. Also, if there are multiple animations on the same screen, they might interfere with each other.
Alternatives
The most obvious alternative to implement the list reorder animation is React Native Reanimated. But it is a heavy library so it is better to consider first if you have the budget to add this additional dependency. Reanimated has lot of features and provides more controls so do consider it if you have lot of animations across the product.
Conclusion
LayoutAnimation in React native is a powerful and general purpose API for basic animations. Although, it is not limited to lists, this article focused only on the list reordering as this was the problem I encountered.
Top comments (1)
An interesting approach indeed!