Search code examples
javascriptreactjsanimationreact-nativereact-native-flatlist

How to animate reorder with React Native FlatList?


I have some UI that looks like this:

enter image description here

These list items can be: (1) added, (2) deleted, (3) reordered.

The reordering is not drag and drop, but happens when clicking the check/empty circle icons - the checked items always stay at the top of the list.

There are many examples of animating adding/removing items from lists in React Native (here's one such example).

But how can I animate the ordering of a list? Specifically in my case, it would be two list items swapping position.

I have seen react-native-sortable-list and a few other open source projects, but I think this is probably overkill as I do not need drag and drop. Also, I am already hooking into some FlatList events like onLayout, onContentSizeChange, and onScroll, so I would prefer a solution that allows me to animate the children of a FlatList directly.


Solution

  • The flatlist is sorted in order of the array that you feed it through the data prop. Whether you are using component-level state (i.e. this.state ) or redux to manage your state, you can reorder the array of elements and it should rerender in that order. For example, one implementation may be:

    const checkedData = [...this.state.data].filter(item => item.checked === true);
    const uncheckedData = [...this.state.data].filter(item => item.checked !== true);
    const sortedData = checkData.concat(uncheckedData);
    this.setState({ data: sortedData });
    

    The javascript filter function should preserve original sort order of the subset.

    To animate it, you can then look into LayoutAnimation in react native. It will apply an animation type to every change in your view between renders.