SmartCodingTips

🌤️ Weather App in React

In this project, you’ll build a weather app using React and the OpenWeatherMap API. You'll learn how to handle forms, fetch data, manage loading/error states, and display real-time weather info.


🔧 1. Setup OpenWeather API

Get your API key from OpenWeatherMap and add it to your .env file:


REACT_APP_WEATHER_API_KEY=your_api_key_here

📦 2. Build the Weather Component


import { useState } from 'react';

function WeatherApp() {
  const [city, setCity] = useState('');
  const [weather, setWeather] = useState(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const fetchWeather = async () => {
    setLoading(true);
    setError('');
    try {
      const res = await fetch(
        `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.REACT_APP_WEATHER_API_KEY}&units=metric`
      );
      if (!res.ok) throw new Error('City not found');
      const data = await res.json();
      setWeather(data);
    } catch (err) {
      setError(err.message);
      setWeather(null);
    }
    setLoading(false);
  };

  return (
    <div className="text-center space-y-6">
      <h2 className="text-2xl font-bold">🌦️ Check Weather</h2>
      <input
        type="text"
        value={city}
        onChange={(e) => setCity(e.target.value)}
        placeholder="Enter city"
        className="px-4 py-2 rounded border dark:bg-gray-800 dark:text-white"
      />
      <button
        onClick={fetchWeather}
        className="bg-blue-600 text-white px-4 py-2 rounded"
      >
        Get Weather
      </button>

      {loading && <p>Loading...</p>}
      {error && <p className="text-red-500">{error}</p>}
      {weather && (
        <div className="mt-4">
          <h3 className="text-xl font-semibold">{weather.name}, {weather.sys.country}</h3>
          <p>🌡 Temp: {weather.main.temp}°C</p>
          <p>🌬 Wind: {weather.wind.speed} m/s</p>
          <p>⛅ Condition: {weather.weather[0].main}</p>
        </div>
      )}
    </div>
  );
}

export default WeatherApp;

🚀 3. Use in App


import WeatherApp from './WeatherApp';

function App() {
  return (
    <main className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-800">
      <WeatherApp />
    </main>
  );
}

export default App;

📋 Summary

  • Used useState for form, data, and error handling
  • Fetched live data using fetch and OpenWeather API
  • Displayed loading and error feedback