<추가 사항>
※OpenWeatherMap 사이트에서 날씨 API 정보를 가져오기
※fetch 함수로 API 서버와 연결
-fetch: 서버로 네트워크 요청을 보내고 응답을 받을 수 있도록 하는 메서드
클라이언트와 서버를 연결시켜줌
※?.(옵셔널 체이닝): 객체 내의 key에 접근할 떄 그 참조가 유효한지 아닌지, 프로퍼티가 없는 중첩 객체를 안전하게 접근
객체 내 값이 null, undefined일 경우 값 반환
※ &units=metric: 섭씨 온도로 변환
componenet
-Input.jsx
-Button.jsx
module
-Login.jsx
-Clock.jsx
-Weather.jsx
page
-ChromeApp.jsx
css
-List.css
img
-1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg
module - <Weather.jsx> : fetch 함수로 API 서버와 연결
import React, {useEffect, useState} from 'react'
function Weather() {
const [weather, setWeather] = useState() //날씨 api 정보
const getWeather = position => {
const lat = position.coords.latitude
const lng = position.coords.longitude
const API_KEY = 'API 키'
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
//&units=metric: 섭씨 온도로 변환
fetch(url) //API 서버와 연결
.then(response => response.json())
.then(data => {
setWeather(data)
})
}
useEffect(() => {
navigator.geolocation.getCurrentPosition(getWeather)
}, [])
return (
<div>
<h1>{weather?.name}</h1> //현재 위치 지역 이름
<h1>{weather?.main.temp}°C</h1> //현재 온도
<img //날씨 아이콘
src={`http://openweathermap.org/img/wn/${weather?.weather[0].icon}@2x.png`}
alt="아이콘"
/>
</div>
)
}
export default Weather
현재 위치 지역 이름, 온도, 날씨 아이콘 출력
'노마드코더 > REACT 크롬 앱' 카테고리의 다른 글
10. 체크박스 체크 유무 확인 (0) | 2024.02.04 |
---|---|
9. 오늘의 할 일 추가, 삭제 (0) | 2024.02.03 |
7. 위도, 경도 불러오기 (0) | 2024.02.01 |
6. Background Image (0) | 2024.01.27 |
5. Clock (0) | 2024.01.25 |