بتل کد Battle Codeدارد باز می‌شود…

مثال JavaScript: <script type="text/jsx"> — فیلتر و جست‌وجو 2 3 4 5

مثال 6 از درس جلسه‌ی 24 آموزش ری‌اکت (React) از صفر برای نوجوانان، قطعه به قطعه: فیلتر و جست‌وجو

فیلتر با چند دکمه هم همین است. state اسم دسته‌ی انتخاب‌شده را نگه می‌دارد ("all"، "fruit" یا "veg"). اگر "all" بود همه را نشان می‌دهیم، وگرنه فقط آن‌هایی را که type آن‌ها همان است.

<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" },
  ];
  const [type, setType] = useState("all");

  const shown = type === "all" ? foods : foods.filter((food) => food.type === type);

  return (
    <div>
      <button onClick={() => setType("all")}>All</button>
      <button onClick={() => setType("fruit")}>Fruit</button>
      <button onClick={() => setType("veg")}>Veg</button>
      <ul>
        {shown.map((food) => (
          <li key={food.id}>{food.name}</li>
        ))}
      </ul>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<App />);
</script>

این کد را همین‌جا در ویرایشگر HTML اجرا کن، عددها و متن‌هایش را عوض کن و دوباره اجرا کن تا ببینی چه تغییری می‌کند.

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js

← مثال قبلی · برگشت به درس جلسه‌ی 24: فیلتر و جست‌وجو · چالش‌های این جلسه