I need to play CSS animation on every time stock property of items state re-renders(increase button clicks)
React code:
const RenderingApp = () => {
const [items, setItems] = useState([
{ fruit: 'banana', stock: 10, id: 0 },
{ fruit: 'apple', stock: 5, id: 1 },
]);
const renderList = () => {
return items.map((item, index) => {
const handleIncrease = () => {
const newItems = items.map(i => {
if (i.id === item.id) {
return { ...i, stock: i.stock + 1 };
} else {
return i;
}
});
setItems(newItems);
};
return (
<div key={index}>
<div>{item.fruit}</div>
<div className="add-color">{item.stock}</div>
<button onClick={handleIncrease}>increase</button>
<br />
<br />
</div>
);
});
};
return <div>{renderList()}</div>;
};
CSS code:
.add-color {
animation-name: example;
animation-duration: 0.8s;
}
@keyframes example {
0% {
background-color: #fff;
}
50% {
background-color: rgb(5, 149, 5);
}
100% {
background-color: #fff;
}
}
However, animation plays once at initial render. To solve this problem, I added key value on the stock's div as it was answered in this question, like so:
<div key={Math.random()} className="add-color">{item.stock}</div>
but now as I click increase button, for example of second item's button, both stock's div re-renders, therefore animation plays for both of them simultaneously:
before I added key value re-render only happened just clicked item's stock div but not played animation, though after adding key value, re-render happens for both item's stock div.
How can I achieve to play animation for just clicked item's stock div? Thanks in advance