Created
August 27, 2023 08:29
-
-
Save gioiliop7/18122fa749783206225576de06eb66c9 to your computer and use it in GitHub Desktop.
[React][Javascript][Tailwind] Weather component with Open weather map api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
const Weather = () => { | |
const [weatherData, setWeatherData] = useState(null); | |
useEffect(() => { | |
const fetchWeatherData = async () => { | |
const apiKey = 'API_KEY'; | |
const place = 'Your Place'; | |
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${place}&units=metric&appid=${apiKey}`; | |
try { | |
const response = await fetch(apiUrl); | |
const data = await response.json(); | |
setWeatherData(data); | |
} catch (error) { | |
console.error('Error fetching weather data:', error); | |
} | |
}; | |
fetchWeatherData(); | |
}, []); | |
return ( | |
<div className="relative md:absolute top-0 right-0 m-4 p-4 bg-white shadow-md rounded-md text-black"> | |
<h2 className="text-lg font-bold mb-2">Weather in {place}</h2> | |
{weatherData ? ( | |
<> | |
<div className="flex items-center"> | |
<img | |
src={`http://openweathermap.org/img/w/${weatherData.weather[0].icon}.png`} | |
alt={weatherData.weather[0].description} | |
className="w-12 h-12 mr-2" | |
/> | |
<div className="text-2xl font-bold">{Math.round(weatherData.main.temp)}°C</div> | |
</div> | |
<div className="text-gray-600 capitalize">{weatherData.weather[0].description}</div> | |
</> | |
) : ( | |
<div>Loading weather data...</div> | |
)} | |
</div> | |
); | |
}; | |
export default Weather; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment