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

جواب «Step 2: City Buttons» چالش 2 از جلسه‌ی 30

سؤال

حالا کاربر شهر را انتخاب کند.
- بالای App (بیرون از آن) بنویس: const CITIES = ["Tehran", "Tabriz", "Shiraz", "Rasht"];
- یک state به اسم city بساز که با "Tehran" شروع شود.
- زیر تیتر یک div با id برابر cities و کلاس row بگذار و با map برای هر شهر یک button با اسم همان شهر بساز که با کلیک city را عوض می‌کند.
- اثر را عوض کن: نشانی "/weather/" + city باشد، لیست [city]، و قبل از گرفتن، weather را null کن تا دوباره Loading... بیاید.

راهنما

دکمه‌ها: {CITIES.map((name) => (<button key={name} onClick={() => setCity(name)}>{name}</button>))}. اثر: setWeather(null); بعد salam.get("/weather/" + city)... با لیست [city].

یک جواب درست

<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; }
.avatar { font-size: 64px; }
.big { font-size: 40px; }
.row { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }
</style>

<div id="root" dir="ltr"></div>

<script type="text/jsx">
import { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";

const ICONS = { Sunny: "☀️", Cloudy: "☁️", Rainy: "🌧️" };

function WeatherCard({ weather }) {
  return (
    <div id="card" className="card">
      <p className="avatar">{ICONS[weather.sky]}</p>
      <h2 id="city">{weather.city}</h2>
      <p id="temp" className="big">{weather.temp}°C</p>
      <p id="sky">{weather.sky}, wind {weather.wind} km/h</p>
    </div>
  );
}

const CITIES = ["Tehran", "Tabriz", "Shiraz", "Rasht"];

function App() {
  const [city, setCity] = useState("Tehran");
  const [weather, setWeather] = useState(null);

  useEffect(() => {
    setWeather(null);
    salam.get("/weather/" + city).then((data) => {
      setWeather(data);
    });
  }, [city]);

  return (
    <div>
      <h1>Weather</h1>
      <div id="cities" className="row">
        {CITIES.map((name) => (
          <button key={name} onClick={() => setCity(name)}>{name}</button>
        ))}
      </div>
      {weather === null && <p id="loading">Loading...</p>}
      {weather !== null && <WeatherCard weather={weather} />}
    </div>
  );
}

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

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن