Categories
React Answers

How to Animate List Reordering with React?

Spread the love

Sometimes, we want to animate list reordering with React

In this article, we’ll look at how to animate list reordering with React

Animate List Reordering with React

To animate list reordering with React, we can use the react-flip-move package.

To install it, we run:

npm i react-flip-move

Then we add the FlipMove component and wrap it around the array of items we want to animate when reordering by writing:

import { shuffle } from "lodash";
import { forwardRef, useState } from "react";
import FlipMove from "react-flip-move";

const Num = forwardRef(({ number }, ref) => <div ref={ref}>{number}</div>);

export default function App() {
  const [nums, setNums] = useState([1, 2, 3, 4, 5]);

  return (
    <div>
      <button onClick={() => setNums((nums) => shuffle(nums))}>shuffle</button>
      <FlipMove>
        {nums.map((n) => (
          <Num key={n} number={n} />
        ))}
      </FlipMove>
    </div>
  );
}

We have the Num component with a ref passed from App with forwardRef .

And we assign the ref to the div.

Next, in App , we create the nums state with an array of items.

Then we add a shuffle button that shuffle nums with the Lodash shuffle function.

Finally, we put the array we want to animate when we shuffle it in the FlipMove component.

Now when we click shuffle, we should see the animation generated with the react-filp-move package.

Conclusion

To animate list reordering with React, we can use the react-flip-move package.

Leave a Reply

Your email address will not be published. Required fields are marked *