Fetching and Displaying Weather Data
0 582
๐ฆ๏ธ Fetching and Displaying Weather Data in React
In this guide, youโll learn how to fetch real-time weather data using an API and display it beautifully in a React app. This is a great way to practice working with external APIs, conditional rendering, and component-based architecture. ๐๐ฒ
๐ Step 1: Get Your API Key
Weโll use the OpenWeatherMap API. To get started:
- Go to OpenWeatherMap.org
- Create a free account and get your API key
โ๏ธ Step 2: Setup React App
npx create-react-app weather-app
cd weather-app
npm start
๐งฑ Step 3: Basic App Structure
Create two components:
SearchBar.jsx: handles city inputWeatherDisplay.jsx: shows weather data
๐ Step 4: Create SearchBar Component
function SearchBar({ onSearch }) {
const [city, setCity] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (city.trim() !== "") onSearch(city);
};
return (
<form onSubmit={handleSubmit} className="flex gap-2">
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
placeholder="Enter city"
className="border p-2 rounded"
/>
<button className="bg-blue-500 text-white p-2 rounded">
Search
</button>
</form>
);
}
๐ค๏ธ Step 5: Fetch and Display Weather Data
function WeatherDisplay({ data }) {
if (!data) return null;
return (
<div className="mt-4 p-4 border rounded bg-white shadow">
<h2 className="text-xl font-bold">๐ {data.name}, {data.sys.country}</h2>
<p>๐ก๏ธ Temp: {Math.round(data.main.temp)}ยฐC</p>
<p>๐ง Humidity: {data.main.humidity}%</p>
<p>๐จ Wind: {data.wind.speed} m/s</p>
<img
src={`https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`}
alt={data.weather[0].description}
/>
<p>{data.weather[0].main}</p>
</div>
);
}
๐ฆ Step 6: Add Logic in App Component
import { useState } from "react";
import SearchBar from "./components/SearchBar";
import WeatherDisplay from "./components/WeatherDisplay";
function App() {
const [weather, setWeather] = useState(null);
const [error, setError] = useState("");
const API_KEY = "YOUR_API_KEY"; // Replace this
const fetchWeather = async (city) => {
setError("");
try {
const res = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`
);
if (!res.ok) throw new Error("City not found");
const data = await res.json();
setWeather(data);
} catch (err) {
setWeather(null);
setError(err.message);
}
};
return (
<div className="max-w-md mx-auto mt-10 p-4">
<h1 className="text-3xl text-center mb-6">๐ค๏ธ Weather App</h1>
<SearchBar onSearch={fetchWeather} />
{error && <p className="text-red-500 mt-4">โ {error}</p>}
<WeatherDisplay data={weather} />
</div>
);
}
๐ก Bonus Tips
- ๐งญ Add geolocation support to show current location weather
- ๐ Add a chart or 5-day forecast using Chart.js or a different API endpoint
- ๐จ Use Tailwind CSS or styled-components for custom styling
๐ Summary
- โ
You learned how to use
fetchto get API data - โ You displayed live weather based on user input
- โ You handled errors and added simple UI components
๐ Final Thoughts
Fetching and displaying weather data is a perfect real-world example of combining API handling and React UI logic. With a few enhancements, this simple app can turn into a weather tracker, location-based tool, or dashboard widget! โ ๐ง
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments