Fetching and Displaying Weather Data
×


Fetching and Displaying Weather Data

744

🌦️ 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:

Save this API key securely — you’ll need it to authenticate your requests.

⚛️ 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 input
  • WeatherDisplay.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 fetch to 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!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat