[React] 주소 검색 라이브러리 react-daum-postcode 사용

Jayden ·2023년 8월 9일
0

1. 라이브러리 설치

npm install react-daum-postcode

2. 주소 양식 input form 구현(상위 컴포넌트)



import React, { useState } from "react"
import DaumPost from "./DaumPost"


(스타일 컴포넌트 구현은 생략하였습니다.)

export default function Signup(){

  
const [popup, setPopup] = useState(false);
  
interface postCode {
        address : string,
        zonecode : number | string,
          
      //zonecode의 string 타입은 초기값 빈 문자열('') 위하여 설정
          
    }

// 상태값 설정        
const [form, setForm] = useState<postCode>({
        address : '',
        zonecode : '',       
 })  
 
 
// 팝업 열고 닫기

const handleComplete = () => {
        setPopup(!popup);
    }  
  
return(
		<AddressWrapper>
                <H4 width={300} marginBottom={8}>주소</H4>
                <Wrapper marginBottom={12}>
                    <Input 
                        borderRadius={12}
                        value={form.zonecode} //선택한 우편번호 input 태그에 바인딩
                        type="text"
                        placeholder="우편번호"
                        backgroundColor="var(--highlight-lightest, #EAF2FF)"
                    />
                    <Button onClick={handleComplete} marginLeft={9}
					borderRadius={12} width ={136}>주소 검색</Button>
                </Wrapper>
                    <Input 
                        borderRadius={12}
                        value={form.address} //선택한 주소값 input 태그에 바인딩 
                        marginBottom={12} 
                        type="text" 
                        placeholder="기본주소" 
                        backgroundColor="var(--highlight-lightest, #EAF2FF)" 
                        width={784}
                    />
                    <Input
                        borderRadius={12}
                        type="text"
                        placeholder="상세주소"
                        minLength={2}
                        maxLength={36}
                        width={784}
                    />
            </AddressWrapper> 
  
  
  // DaumPost 컴포넌트에서 상태값을 설정할 수 있도록 props을 전달합니다
  
		{popup && <DaumPost address={form} setAddress = {setForm} handleComplete={handleComplete}/>}
        ...
)        

3. 컴포넌트 작성(DaumPost 컴포넌트)

import DaumPostcode from "react-daum-postcode"
import { styled } from "styled-components"
import { ReactComponent as DaumPostCloseSvg} from "../images/CloseWhite.svg"

const DaumPostBackground = styled.div`
    position :fixed;
    top : 0;
    left : 0;
    bottom : 0;
    right : 0;
    background : rgba(0, 0, 0, 0.8);
`

const DaumPostContainer = styled.div`

    width : 500px;
    position : absolute;
    left : 50%;
    top: 50%;
    transform : translate(-50%, -50%);

`

/* 다음 주소 검색 API에서 주소를 검색 후 주소를 클릭 시 창이 닫힙니다.

이때, complete 함수로 클릭한 주소 정보(주소(fullAddress), 

우편번호(zonecode))를 변수에 저장후 이 값을 상태값(form 값)으로 설정합니다. */


export default function DaumPost(props : any){

  
  /* 아래 함수로 들어오는 파라미터 (data)의 정체가 무엇일까를
  생각해 보았는데 DaumPostcode props중에 onComplete가 있는데,
  주소를 클릭하고 창이 닫힐때
  선택한 주소에 대한 파라미터 정보가 이곳으로 전달되는 것 같습니당..... */

    const complete = (data : any) =>{
        let fullAddress = data.address;
        let zonecode = data.zonecode
        let extraAddress = '';

        if (data.addressType === 'R') {
            if (data.bname !== '') {
                extraAddress += data.bname;
            }
            if (data.buildingName !== '') {
                extraAddress += (extraAddress !== '' ? `, ${data.buildingName}` : data.buildingName);
            }
            fullAddress += (extraAddress !== '' ? ` (${extraAddress})` : '');
        }
        console.log(data)
        console.log(fullAddress)
        console.log(data.zonecode)

        // 선택한 주소값을 상태값으로 설정
        props.setAddress({
            ...props,
            address:fullAddress,
            zonecode:zonecode,
        })

        // 팝업창 닫기(팝업창 'X' 표시)
        props.handleComplete();

    }
        return(
            <DaumPostBackground>
                <DaumPostContainer>
                <div style={{display : "flex", justifyContent : "space-between"}}>  
                    <h1 style={{color : "#fff", height : "50px", width : "500px"}}>주소 검색</h1>
                    <DaumPostCloseSvg  onClick={()=> {props.handleComplete()}}/>
                </div>  
                <DaumPostcode
                    autoClose
                    style={{
                    height : "500px", width : "500px"}}
                    onComplete={complete} /> 
                </DaumPostContainer>   
            </DaumPostBackground>     
        )
}

4. 사용해 보기

console.log(JSON.stringify(form))

주소를 클릭하면 창이 닫히는 동시에 콘솔에 검색한 주소 정보가 표시됩니다.

input Text Field에도 잘 표시됩니다.

profile
프론트엔드 개발자

0개의 댓글