[React Native -14] 다음 주소 검색 API 이용하기
진행하고 있는 프로젝트에서 상품을 주문을 할 때 주소 검색 API를 사용할 일이 생겼다
1. 행정안전부 도로명 주소 API
2. 다음 주소 API
도로명개발자 센터에서 제공하는 API가 있지만 실제로 다음 주소가 훨씬 많이 쓰이며 key 발급도 필요 없고 사용법도 매우 편리하다
구글링을 하던 중, 대부분의 사람들이 react-daum-postcode 라이브러리를 사용한다는 것을 알게되었다
✅ 다음 postcode 라이브러리 설치
npm install @actbase/react-daum-postcode
✅ WebView 라이브러리 설치
npm install react-native-webview
https://github.com/actbase/react-daum-postcode
GitHub - actbase/react-daum-postcode: 다음 우편번호찾기 Bridge for React, React-Native, RNW
다음 우편번호찾기 Bridge for React, React-Native, RNW. Contribute to actbase/react-daum-postcode development by creating an account on GitHub.
github.com
주소 검색 API를 사용할 페이지에 import 해준다
import Postcode from '@actbase/react-daum-postcode';
<Postcode
style={{ width: '100%', height: '100%' }}
jsOptions={{ animation: true }}
onSelected={data => alert(JSON.stringify(data))}
/>
onSelected : 결과값을 클릭할 때 실행되는 함수
* alert 창과 console에 JSON 데이터를 가져오는 것을 볼 수 있다
필요한 데이터값만 추출해서 navigate로 params을 보내면 된다
SearchAddress.js
import React, { Component } from 'react';
import Postcode from '@actbase/react-daum-postcode';
class SearchAddress extends Component {
constructor(props) {
super(props);
}
getAddressData=(data)=>{
let defaultAddress='';
if(data.buildingName==='')
{
defaultAddress='';
}
else if(data.buildingName==='N')
{
defaultAddress="("+data.apartment+")";
}
else{
defaultAddress="("+data.buildingName+")";
}
this.props.navigation.navigate('Drawers',{screen:'Deliver', params:{zonecode:data.zonecode, address:data.address, defaultAddress:defaultAddress}});
}
render() {
return (
<Postcode
style={{ width: '100%', height: '100%' }}
jsOptions={{ animation: true }}
onSelected={(data)=>this.getAddressData(data)}
/>
)
}
}
export default SearchAddress;
Address.js
<View style={styles.number_text}>
<Text style={styles.text}>{this.props.route.params.zonecode}</Text>
</View>
<TouchableOpacity activeOpacity={0.8} style={styles.btn} onPress={()=>this.props.navigation.push('Stack',{screen:'DeliverView'})}>
<Text style={styles.btn_text}>우편번호 찾기</Text>
</TouchableOpacity>
<View style={styles.address_text}>
<Text style={styles.text}>{this.props.route.params.address+' '+this.props.route.params.defaultAddress}</Text>
</View>
<TextInput style={template.textInput}
placeholder="상세 주소를 입력하세요"/>
결과물
정말 간단하게 구현할 수 있는 것을 알 수 있다 😁