بتل کد 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... بیاید.

<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; }
</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>
  );
}

function App() {
  const [weather, setWeather] = useState(null);

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

  return (
    <div>
      <h1>Weather</h1>
      {weather === null && <p id="loading">Loading...</p>}
      {weather !== null && <WeatherCard weather={weather} />}
    </div>
  );
}

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

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 30: پروژه: اپ هواشناسی · چالش بعدی: Step 3: Search and Errors

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