I'm trying to animate the vertical position of elements within a list using ReactJS. The elements can be arbitrarily ordered within the list, however they all have unique identifiers.
The elements in the list have a static height and only their vertical position changes.
I'm able to apply transform: translate(0px, ${index * height}px) to each element and use transition: transform 1s ease-in-out to animate changes to the translation. This results in the elements being rendered in the appropriate order.
However when the elements are re-ordered, only elements moving "up" are animated; elements which end up further below are "snapped" into place automatically.
Ideally I'd want to do this without the help of a library unless the problem is harder than I think it is to solve.
import shuffle from "lodash.shuffle";
import { useState } from "react";
const data = [
{ id: 1, name: "Foo" },
{ id: 2, name: "Bar" },
{ id: 3, name: "Baz" }
];
export default function App() {
const [items, setItems] = useState(data);
return (
<div>
<button
onClick={() => {
setItems(shuffle(data));
}}
>
Shuffle
</button>
<div style={{ position: "relative" }}>
{items.map(({ id, name }, index) => (
<div
key={id}
style={{
position: "absolute",
border: "1px solid #ddd",
width: "100%",
height: 42,
boxSizing: "border-box",
transition: "transform 1s ease-in-out",
transform: `translate(${0}px, ${index * 42}px)`
}}
>
{name}
</div>
))}
</div>
</div>
);
}