專案目標
今天是最後一天了!
前面學了JavaScript許多東西,所以就來把之前學過的東西做成專案吧!
今天我們來製作一個可以查詢即時天氣的小App!
功能
建立專案
使用 Create React App:
npx create-react-app weather-app
cd weather-app
npm start
申請免費 API Key
到OpenWeatherMap 註冊帳號後,取得一組免費的API key
我們要用三個主要部分來組成這個App:
import React, { useState } from "react";
function WeatherApp() {
const [city, setCity] = useState("");
const [weather, setWeather] = useState(null);
const [error, setError] = useState("");
const API_KEY = "API_KEY"; //換成自己的
const getWeather = async () => {
if (!city) return;
try {
setError("");
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric&lang=zh_tw`
);
if (!response.ok) {
throw new Error("找不到這個城市,請再試一次!");
}
const data = await response.json();
setWeather(data);
} catch (err) {
setWeather(null);
setError(err.message);
}
};
return (
<div className="flex flex-col items-center p-6 bg-blue-100 min-h-screen">
<h1 className="text-2xl font-bold mb-4">天氣查詢小工具</h1>
<div className="flex gap-2 mb-4">
<input
type="text"
placeholder="輸入城市名稱..."
value={city}
onChange={(e) => setCity(e.target.value)}
className="border p-2 rounded"
/>
<button
onClick={getWeather}
className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
查詢
</button>
</div>
{error && <p className="text-red-600">{error}</p>}
{weather && (
<div className="bg-white p-4 rounded shadow-md w-64 text-center">
<h2 className="text-xl font-semibold mb-2">{weather.name}</h2>
<p>{weather.weather[0].description}</p>
<p>溫度:{weather.main.temp} °C</p>
<p>濕度:{weather.main.humidity}%</p>
</div>
)}
</div>
);
}
export default WeatherApp;