(react) Weather API
2023-04-01
![](https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2Ffd0a4819-d724-4acd-849f-e59120e8dcea%2FUntitled.png?table=block&id=80bf57e9-6f60-42a0-9ccb-e6584924914b&spaceId=4f129cb2-a39f-45b1-9039-9f7e5c0b105d&width=1710&userId=c74defa9-702d-447e-9448-63360907d57e&cache=v2)
API 키 받아오기
https://openweathermap.org/여기서 날씨 api의 키를 발급받아 사용했습니다.
React 컴포넌트 만들기
가장 먼저 나는 박스 형태로 날씨를 나타내게 하기 위해 App 컴포넌트 아래에 Weather 컴포넌트를 따로 만들어줬습니다.
const Weather = () => {}
다음으로는 가장 먼저 지역에 따라 온도와 날씨 아이콘과 배경 이미지를 표시하기 위해 fetch를 이용해 API를 받아오고 useState로 만들어줬습니다. 그리고 배경 이미지는 날씨에 따라 다르게 만들어줬습니다.
let [location, setlocation] = useState("Seoul"); // 지역상태
let [weather, setWeather] = useState("Clear"); // 날씨 상태
let [icon, setIcon] = useState(); // 날씨 아이콘 상태
let [temp, setTemp] = useState(); // 온도 상태
const API_KEY = process.env.REACT_APP_WEATHER_KEY;
const url = `https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${API_KEY}`
let weather_api = fetch(url);
weather_api
.then((response) => response.json())
.then((data) => {setTemp(data.main.temp); setWeather(data.weather[0].main); setIcon(data.weather[0].icon)})
다음으로는 셀렉트 박스를 이용해 지역을 변경하면 지역 상태가 변경되게 해줍니다.
const location_trans = (e) => {
setlocation(e.target.value);
}
다음은 날씨에 따라 배경이 변하게 해주기 위해 CSS 변수를 생성해줍니다.
let weather_img_css = {
backgroundImage: `url(image/${weather}.jpg)`,
backgroundSize: 'cover'
}
마지막으로 JSX를 리턴해주면 끝입니다. 엄청 간단하죠?
return (
<section id = 'home-box' style = {weather_img_css}>
<div className = "inner-box">
<div className = "temp">{(temp - 273.15).toFixed(1)}°C</div>
<img src = {`icon/${icon}.png`} alt = "weather-icon" style = {{width: '50px', height: '50px'}}></img>
<select name = 'location' id = 'select-box' onChange = {location_trans}>
<option value = "Seoul">Seoul</option>
<option value = "Incheon">Incheon</option>
<option value = "Busan">Busan</option>
<option value = "Daejeon">Daejeon</option>
<option value = "Gwangju">Gwangju</option>
<option value = "Daegu">Daegu</option>
<option value = "Ulsan">Ulsan</option>
<option value = "Jeju">Jeju</option>
</select>
</div>
</section>
)
CSS 코드
#home-box {
width: 500px;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 10px;
box-shadow: 0 0 10px 5px rgba(0, 0, 0, 0.459);
}
.inner-box {
width: 250px;
height: 300px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: rgba(119, 119, 119, 0.493);
border-radius: 10px;
box-shadow: 0 0 10px 5px rgba(255, 255, 255, 0.5);
}
.temp {
width: auto;
height: auto;
font-size: xxx-large;
color: white;
}
#select-box {
width: 190px;
height: 20px;
color: rgb(0, 0, 0);
background-color: rgba(255, 255, 255, 0.541);
border-radius: 5px;
}
option {
border-radius: 10px;
background-color: rgba(138, 138, 138, 0.548);
}
option:active {
background-color: white;
}