Search code examples
reactjsanimationmotionframer-motion

React - Framer Motion animates only the last item in map


so I have a state with an array, and I'm mapping it with framer motion animation. The problem is that I'm adding an item to the first position on the array, not at the end. So when a new item is added, instead of animating the new item added to the array, framer motion animates always the last one. Here is my code:

const [list, setList] = useState([])

const addToList = () => {
    let newElement = (Math.random() + 1).toString(36).substring(7)
    setList(prevState => ([newElement, ...prevState]))
}

return (
    <div className="flex flex-col bg-white h-screen">
        <button onClick={() => addToList()} className="bg-blue-500 p-2 rounded-lg text-white">Add to List</button>
        <p className="mt-2">List:</p>
        <div className="flex flex-col mt-4">
            {
                list.map((l, i) => {
                    return (
                        <motion.div initial={{ scale: 0 }} animate={{ scale: 1 }}>
                            <p key={i}>{l}</p>
                        </motion.div>
                    )
                })
            }
        </div>
    </div>
)

Always the same last item animates when a new item is added (instead of the new item that will be the first position at the array). How can I solve it?


Solution

  • Problem solved. I was using a key based on the array position of the element, so when a new element was added, React have to render everything again (I think). By using a unique key, React knows exactly what item was changed (added in this case). So the animation works fine.