جواب «Fruit or Veg» چالش 5 از جلسهی 24
سؤال
سه دکمه و فهرست غذاها آمادهاند، ولی دکمهها کاری نمیکنند. فیلتر را خودت بساز:
- یک state به اسم type که اولش "all" است.
- دکمهی #all آن را "all"، دکمهی #fruit آن را "fruit" و دکمهی #veg آن را "veg" کند.
- shown حساب شود: اگر type برابر "all" بود همهی غذاها، وگرنه فقط غذاهایی که type آنها همان است.
- یک p با id برابر info بنویسد چند غذا دیده میشود: Showing 5
راهنما
const [type, setType] = useState("all"); و const shown = type === "all" ? foods : foods.filter((food) => food.type === type);. روی دکمه: onClick={() => setType("fruit")}.
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
ul { list-style: none; padding: 0; }
li { margin: 6px 0; }
</style>
<div id="root" dir="ltr"></div>
<script type="text/jsx">
import { useState } from "react";
import { createRoot } from "react-dom/client";
function App() {
const foods = [
{ id: 1, name: "Apple", type: "fruit" },
{ id: 2, name: "Carrot", type: "veg" },
{ id: 3, name: "Banana", type: "fruit" },
{ id: 4, name: "Onion", type: "veg" },
{ id: 5, name: "Cherry", type: "fruit" },
];
const [type, setType] = useState("all");
const shown = type === "all" ? foods : foods.filter((food) => food.type === type);
return (
<div>
<button id="all" onClick={() => setType("all")}>All</button>
<button id="fruit" onClick={() => setType("fruit")}>Fruit</button>
<button id="veg" onClick={() => setType("veg")}>Veg</button>
<p id="info">Showing {shown.length}</p>
<ul id="list">
{shown.map((food) => (
<li key={food.id}>{food.name}</li>
))}
</ul>
</div>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن