Step 1: Set Up Your React Project
Open your terminal and run the following commands:
bashCopy codenpx create-react-app weather-app
cd weather-app
Step 2: Get Your API Key
- Go to OpenWeatherMap and sign up for a free account.
- After logging in, navigate to the API section and get your API key.
Step 3: Create the Weather App Component
Open src/App.js
and replace its content with the following code:
javascriptCopy codeimport React, { useState } from 'react';
import './App.css';
const App = () => {
const [city, setCity] = useState('');
const [weather, setWeather] = useState(null);
const [error, setError] = useState('');
const API_KEY = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key
const handleInputChange = (e) => {
setCity(e.target.value);
};
const fetchWeather = async () => {
if (!city) return;
try {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
if (!response.ok) {
throw new Error('City not found');
}
const data = await response.json();
setWeather(data);
setError('');
} catch (err) {
setError(err.message);
setWeather(null);
}
};
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
fetchWeather();
}
};
return (
<div className="App">
<h1>Weather App</h1>
<input
type="text"
value={city}
onChange={handleInputChange}
onKeyPress={handleKeyPress}
placeholder="Enter city name..."
/>
<button onClick={fetchWeather}>Get Weather</button>
{error && <p className="error">{error}</p>}
{weather && (
<div className="weather-info">
<h2>{weather.name}</h2>
<p>Temperature: {weather.main.temp} °C</p>
<p>Weather: {weather.weather[0].description}</p>
<p>Humidity: {weather.main.humidity} %</p>
<p>Wind Speed: {weather.wind.speed} m/s</p>
</div>
)}
</div>
);
};
export default App;
Step 4: Style Your App
Open src/App.css
and add some basic styles:
cssCopy code.App {
text-align: center;
margin: 20px;
font-family: Arial, sans-serif;
}
input {
padding: 10px;
margin-right: 10px;
width: 200px;
}
button {
padding: 10px;
}
.weather-info {
margin-top: 20px;
}
.error {
color: red;
}
Step 5: Run Your Application
In the terminal, run:
bashCopy codenpm start
Leave a Reply