Fetching and Displaying Weather Data
×


Fetching and Displaying Weather Data

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:

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

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat