14 - Weather Widget with Temperature and Description
Description
Create a React application that displays a weather widget with the current temperature and description for a given location. The user should be able to select their city from a dropdown list.
Algorithm
Create a dropdown list of cities using a select element.
Use an API to fetch the current weather data for the selected city.
Parse the API response to extract the temperature and description.
Render a widget with the temperature and description.
Classes
WeatherWidget
: A component that renders the dropdown list, fetches the weather data, and renders the widget.
Code
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function WeatherWidget() {
const [city, setCity] = useState('New York');
const [weather, setWeather] = useState(null);
useEffect(() => {
axios.get("<url-to-fetch-weather-data")
.then(response => {
setWeather(response.data);
});
}, [city]);
const handleCityChange = (event) => {
setCity(event.target.value);
};
return (
<div>
<select value={city} onChange={handleCityChange}>
<option value="New York">New York</option>
<option value="Los Angeles">Los Angeles</option>
<option value="Chicago">Chicago</option>
<!-- Add more cities here -->
</select>
{weather && (
<div>
<p>Temperature: {weather.main.temp}°C</p>
<p>Description: {weather.weather[0].description}</p>
</div>
)}
</div>
);
}
export default WeatherWidget;
Explanation
The WeatherWidget
component renders a dropdown list of cities using a select element. When the user selects a city, the component fetches the weather data from the OpenWeatherMap API using the axios
library. The component then renders a widget with the temperature and description.
Possible Future Enhancements
Add more cities to the dropdown list.
Use a more advanced API (e.g., Dark Sky, Weather Underground).
Display additional weather data (e.g., humidity, wind speed).
Display a loading indicator while the data is being fetched.
Style the widget with CSS.
Last updated