1
0
Fork 0

reactive state: remove item from list

This commit is contained in:
Henrik Hautakoski 2025-11-13 22:00:18 +01:00
parent bf231dd1d6
commit 927f61abf8

View file

@ -1,3 +1,5 @@
import { useState } from "react";
const products = [ const products = [
{ title: 'Cabbage', isFruit: false, id: 1 }, { title: 'Cabbage', isFruit: false, id: 1 },
{ title: 'Garlic', isFruit: false, id: 2 }, { title: 'Garlic', isFruit: false, id: 2 },
@ -5,8 +7,14 @@ const products = [
]; ];
function App() { function App() {
const listItems = products.map(product => const [items, setItems] = useState(products);
<li
function remove(id:number) {
setItems(items.filter((item) => item.id !== id))
}
const list = items.map(product =>
<li onClick={() => remove(product.id)}
key={product.id} key={product.id}
className={product.isFruit ? 'text-green-200' : 'text-red-200'}> className={product.isFruit ? 'text-green-200' : 'text-red-200'}>
{product.title} {product.title}
@ -16,7 +24,7 @@ function App() {
return ( return (
<div className="mx-auto flex flex-col items-center space-y-4 text-white"> <div className="mx-auto flex flex-col items-center space-y-4 text-white">
<h1 className="text-2xl">Shopping list</h1> <h1 className="text-2xl">Shopping list</h1>
<ul className="list-disc">{listItems}</ul> <ul className="list-disc">{list}</ul>
</div> </div>
) )
} }