جواب «Step 4: Search» چالش 4 از جلسهی 25
سؤال
آخرین بخش: جستوجو در قفسه.
1. در App یک state به اسم query بساز که اولش "" است.
2. زیر تیتر یک input با id برابر search بگذار که به query وصل است (value و onChange).
3. shown را حساب کن: کالاهایی از PRODUCTS که query داخل اسمشان هست. حرف بزرگ و کوچک فرقی نکند. قفسه بهجای PRODUCTS همین shown را نشان بدهد.
4. وقتی هیچ کالایی پیدا نشد، یک p با id برابر none و متن No products found دیده شود.
سبد نباید با جستوجو عوض شود.
راهنما
const shown = PRODUCTS.filter((item) => item.name.toLowerCase().includes(query.toLowerCase())); و <input id="search" value={query} onChange={(e) => setQuery(e.target.value)} />. در قفسه بنویس shown.map.
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.card { max-width: 260px; margin: 12px auto; padding: 16px; border: 2px solid #334155; border-radius: 16px; background: #f8fafc; }
ul { list-style: none; padding: 0; }
li { margin: 6px 0; }
li button { min-height: 36px; }
</style>
<div id="root" dir="ltr"></div>
<script type="text/jsx">
import { useState } from "react";
import { createRoot } from "react-dom/client";
const PRODUCTS = [
{ id: 1, name: "Apple", price: 2 },
{ id: 2, name: "Bread", price: 3 },
{ id: 3, name: "Milk", price: 4 },
{ id: 4, name: "Cake", price: 6 },
];
function Product({ item, inCart, onAdd }) {
return (
<li>
{item.name}: {item.price} coins
<button id={"add-" + item.id} disabled={inCart} onClick={() => onAdd(item)}>Add</button>
</li>
);
}
function Cart({ items, onRemove }) {
let total = 0;
for (const item of items) {
total += item.price;
}
return (
<div id="cart-box" className="card">
<h2>Cart</h2>
<p id="count">In cart: {items.length}</p>
{items.length === 0 && <p id="empty">Your cart is empty</p>}
<ul id="cart">
{items.map((item) => (
<li key={item.id}>
{item.name}
<button id={"remove-" + item.id} onClick={() => onRemove(item.id)}>Remove</button>
</li>
))}
</ul>
<p id="total">Total: {total}</p>
</div>
);
}
function App() {
const [cart, setCart] = useState([]);
const [query, setQuery] = useState("");
const shown = PRODUCTS.filter((item) => item.name.toLowerCase().includes(query.toLowerCase()));
function addToCart(item) {
setCart([...cart, item]);
}
function removeFromCart(id) {
setCart(cart.filter((item) => item.id !== id));
}
return (
<div>
<h1>Little Shop</h1>
<input id="search" placeholder="Search" value={query} onChange={(e) => setQuery(e.target.value)} />
{shown.length === 0 && <p id="none">No products found</p>}
<ul id="products">
{shown.map((item) => (
<Product key={item.id} item={item} inCart={cart.includes(item)} onAdd={addToCart} />
))}
</ul>
<Cart items={cart} onRemove={removeFromCart} />
</div>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن