A React Weather App using the OpenWeatherMap API.
Steps to Set Up the Project
- Create a new React app:
npx create-react-app weather-app cd weather-app npm start
- Get an API Key from OpenWeatherMap:
- Sign up and get a free API key.
Install Axios for API Requests
Run the following command inside your project folder:
npm install axios
Code for src/App.js
import React, { useState } from "react";
import axios from "axios";
const API_KEY = "YOUR_OPENWEATHERMAP_API_KEY"; // Replace with your API Key
const API_URL = "https://api.openweathermap.org/data/2.5/weather";
function App() {
const [city, setCity] = useState("");
const [weather, setWeather] = useState(null);
const [error, setError] = useState(null);
const fetchWeather = async () => {
if (!city.trim()) return;
try {
const response = await axios.get(API_URL, {
params: {
q: city,
appid: API_KEY,
units: "metric", // Get temperature in Celsius
},
});
setWeather(response.data);
setError(null);
} catch (err) {
setWeather(null);
setError("City not found. Please try again!");
}
};
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>Weather App 🌤</h1>
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
placeholder="Enter city name..."
/>
<button onClick={fetchWeather}>Get Weather</button>
{error && <p style={{ color: "red" }}>{error}</p>}
{weather && (
<div>
<h2>{weather.name}, {weather.sys.country}</h2>
<h3>{weather.main.temp}°C</h3>
<p>{weather.weather[0].description.toUpperCase()}</p>
<img
src={`https://openweathermap.org/img/wn/${weather.weather[0].icon}.png`}
alt="Weather icon"
/>
</div>
)}
</div>
);
}
export default App;
How It Works
✅ User enters a city name
✅ Click “Get Weather”
✅ Fetches live weather data from OpenWeatherMap
✅ Displays city name, temperature, weather condition, and icon
Optional Enhancements
- Use Tailwind CSS or Bootstrap for styling.
- Display humidity, wind speed, etc.
- Implement geolocation to get weather for the user’s location.