Weather App 1
Thu Jun 29 2023 17:21:14 GMT+0000 (Coordinated Universal Time)
Saved by
@mooose22
#javascript
import React, { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [data, setData] = useState({});
const [location, setLocation] = useState("");
const [showResults, setShowResults] = useState(false);
const url = `https://api.openweathermap.org/data/2.5/weather?q=${location}&units=imperial&appid=80e8dda85f86ac0d7028efe74f5b553e`;
const fetchData = async () => {
const response = await axios.get(url);
setData(response.data);
console.log(response.data);
setShowResults(true);
setTimeout(() => {
setShowResults(false);
setLocation("");
}, 3000);
};
const handleSearch = () => {
fetchData();
};
const handleLocationChange = (event) => {
setLocation(event.target.value);
};
const handleKeyPress = (event) => {
if (event.key === "Enter") {
handleSearch();
}
};
return (
<div className="app">
<div className="search">
<input
type="text"
value={location}
onChange={handleLocationChange}
onKeyDown={handleKeyPress}
placeholder="EnterLocation"
/>
<button onClick={handleSearch}>Search</button>
</div>
{showResults && (
<div className="top">
<div className="temp">
{data.main ? <h1>{data.main.temp.toFixed()}°F</h1> : null}
</div>
</div>
)}
</div>
);
}
export default App;
// CSS
.app {
max-width: 400px;
margin: 3rem auto;
padding: 20px;
}
.search {
display: flex;
align-items: center;
margin-bottom: 20px;
}
input[type="text"] {
width: 200px;
padding: 8px;
border-radius: 4px;
border: 1px solid #ccc;
margin-right: 10px;
}
button {
padding: 8px 16px;
border-radius: 4px;
background-color: #4caf50;
color: white;
border: none;
cursor: pointer;
}
content_copyCOPY
Comments