yarn add react-daum-postcode
type TextRadioValueType = {
title: string,
contents: string,
price: number,
count: number,
exchange_product: string,
tags: string[],
shipping_cost: string,
deal_type: string,
quality: string,
changable: string,
address: string,
detailAddress: string
}
const productsPostsTextInit: TextRadioValueType = {
title: "",
contents: "",
price: 0,
count: 0,
exchange_product: "",
tags: [],
shipping_cost: "",
deal_type: "",
quality: "",
changable: "",
address: "",
detailAddress: ""
}
const ProductsWriteForm = () => {
...(중략)
return (
<div>
<h2>직거래 지역</h2>
<AddressBtn
textRadioValue={textRadioValue}
setTextRadioValue={setTextRadioValue} />
<input readOnly type='text' name='address'
value={textRadioValue.address}
onChange={handleOnChangeTextRadioValue}
placeholder='주소검색을 이용해주세요.' />
<input type='text' name='detailAddress'
value={textRadioValue.detailAddress}
onChange={handleOnChangeTextRadioValue}
placeholder='상세주소를 입력해주세요.' />
</div>
)
};
* 전체코드
import { useDaumPostcodePopup } from 'react-daum-postcode';
interface Props {
scriptUrl?: string,
textRadioValue: TextRadioValueType,
setTextRadioValue: React.Dispatch<React.SetStateAction<TextRadioValueType>>
}
const AddressBtn = ({scriptUrl, textRadioValue, setTextRadioValue}: Props) => {
const open = useDaumPostcodePopup(scriptUrl);
const handleComplete = (data: any) => {
let fullAddress = data.address;
let extraAddress = "";
if (data.addressType === "R") {
if (data.bname !== "") {
extraAddress += data.bname;
}
if (data.buildingName !== "") {
extraAddress += extraAddress !== "" ? `, ${data.buildingName}` : data.buildingName;
}
fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
}
// 입력된 주소 값(fullAddress)을 상태 값의 address에 바꿔 넣기
setTextRadioValue(prev => ({ ...prev, address: fullAddress }));
};
const handleOnClickAddressBtn = (e: React.MouseEvent<HTMLButtonElement>) => {
open({ onComplete: handleComplete });
e.preventDefault();
};
return (
<div>
<button onClick={handleOnClickAddressBtn}>주소 검색</button>
</div>
);
}
export default AddressBtn
<div>
<h2>직거래 지역</h2>
<AddressBtn
textRadioValue={textRadioValue}
setTextRadioValue={setTextRadioValue} />
<input readOnly type='text' name='address'
value={textRadioValue.address}
disabled={textRadioValue.deal_type === '택배' || textRadioValue.deal_type === '협의 후 결정'}
onChange={handleOnChangeTextRadioValue}
placeholder='주소검색을 이용해주세요.' />
<input type='text' name='detailAddress'
value={textRadioValue.detailAddress}
disabled={textRadioValue.deal_type === '택배' || textRadioValue.deal_type === '협의 후 결정'}
onChange={handleOnChangeTextRadioValue}
placeholder='상세주소를 입력해주세요.' />
</div>