Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 90 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,123 @@
# react-daum-postcode

리액트 컴포넌트로 만든 Daum 우편번호 검색 서비스입니다. Daum 우편번호 검색 서비스를 React 환경에서 간편하게 이용할 수 있습니다.
Daum 우편번호 검색 서비스를 React 환경에서 간편하게 이용할 수 있습니다.

## 설치
## Install

```shell
npm install --save react-daum-postcode
// or
yarn add react-daum-postcode
```

## 사용
## Embed

`DaumPostcodeEmbed` 컴포넌트를 사용하여, 우편번호 검색 서비스를 임베드 방식으로 사용할 수 있습니다.

```javascript
import React from 'react';
import DaumPostcodeEmbed from 'react-daum-postcode';

const Postcode = () => {
const handleComplete = (data) => {
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})` : '';
}

console.log(fullAddress); // e.g. '서울 성동구 왕십리로2길 20 (성수동1가)'
};

return <DaumPostcodeEmbed onComplete={handleComplete} {...props} />;
};
```

`DaumPostcodeEmbed` 컴포넌트에 다음 우편번호 서비스의 생성자 및 임베드 설정값 등을 `props`로 전달할 수 있습니다. 전달하지 않은 설정값은 다음 우편번호 서비스의 기본 설정을 따라갑니다.

| name | type | default | description
|:----:|:----:|:-------:|:-----------|
| scriptUrl | `string` | [CURRENT_URL](https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js) | Daum 우편번호 서비스의 스크립트 주소입니다.|
| onComplete | `function` | `undefined` | 우편번호 검색이 끝났을 때 사용자가 선택한 정보를 받아올 콜백함수입니다. 주소 데이터의 구성은 [Daum 가이드](http://postcode.map.daum.net/guide)를 참고해주세요. |
| onSearch | `function` | `undefined` | 주소를 검색할 경우 실행되는 콜백함수입니다. 검색 결과 정보의 구성은 [Daum 가이드](http://postcode.map.daum.net/guide)를 참고해주세요. |
| onClose | `function` | `undefined` | 검색 결과를 선택하여, 서비스가 닫힐 때 실행되는 콜백함수입니다. |
| onResize | `function` | `undefined` | 검색 결과로 인해, 우편번호 서비스의 화면 크기가 변경될 때 호출되는 콜백함수입니다. 변경된 화면 정보의 구성은 [Daum 가이드](http://postcode.map.daum.net/guide)를 참고해주세요. |
| className | `string` | `undefined` | 우편번호 검색창을 감싸는 최상위 엘리먼트에 적용할 클래스 이름입니다. |
| style | `object` | `{ width:"100%", height:400 }` | 우편번호 검색창을 감싸는 최상위 엘리먼트에 적용할 스타일입니다. |
| defaultQuery | `string` | `undefined` | 우편번호 검색창에 기본으로 입력할 검색어입니다.
| autoClose | `boolean` | `true` | 우편번호 검색 완료시 자동 닫힘 여부입니다. 주소를 선택하면, 최상위 엘리먼트를 돔에서 제거합니다. |
| errorMessage | `ReactNode` | `<p>현재 Daum 우편번호 서비스를 이용할 수 없습니다. 잠시 후 다시 시도해주세요.</p>` | 우편번호 서비스 스크립트 로드에 실패했을 때 나타낼 에러 메세지 입니다. |

기타 Daum 우편번호 생성자 속성들을 동일한 이름으로 props를 전달할 수 있습니다. 속성값에 대해서는 [Daum 우편번호 서비스 가이드](http://postcode.map.daum.net/guide#attributes)를 참고해주세요.

## Popup

`useDaumPostcodePopup` hook 을 사용하여, 반환받은 함수를 통해 우편번호 검색 서비스를 팝업 방식으로 이용할 수 있습니다.

```javascript
import React from 'react';
import DaumPostcode from 'react-daum-postcode';
import { useDaumPostcodePopup } from 'react-daum-postcode';

const Postcode = () => {
const open = useDaumPostcodePopup(scriptUrl);

const handleComplete = (data) => {
let fullAddress = data.address;
let extraAddress = '';
let extraAddress = '';

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

console.log(fullAddress); // e.g. '서울 성동구 왕십리로2길 20 (성수동1가)'
}
console.log(fullAddress); // e.g. '서울 성동구 왕십리로2길 20 (성수동1가)'
};

const handleClick = () => {
open({ onComplete: handleComplete });
};

return (
<DaumPostcode
onComplete={handleComplete}
{ ...props }
/>
<button type='button' onClick={handleClick}>
Open
</button>
);
}
};
```

## props

- `onComplete` _[function]_ - 우편번호 검색이 끝났을 때 사용자가 선택한 정보를 받아올 콜백함수입니다.
- `function(data: object) => void` : 주소 데이터의 구성은 [Daum 우편번호 서비스 가이드](http://postcode.map.daum.net/guide)를 참고해주세요.
- `onSearch` _[function]_ - 주소를 검색할 경우에 실행되는 콜백함수입니다.
- `function(data: object) => void` : 검색결과 정보의 구성은 [Daum 우편번호 서비스 가이드](http://postcode.map.daum.net/guide)를 참고해주세요.
- `onClose` _[function]_ - 검색 결과를 선택하여, 우편번호 검색이 닫힐 때 실행되는 콜백함수입니다.
- `onResize` _[function]_ - 검색 결과로 인해, 우편번호 서비스의 화면 크기가 변경될 때 실행되는 콜백함수입니다.
- `className` _[string]_ - 우편번호 검색창을 감싸는 최상위 엘리먼트에 적용할 클래스명입니다.
- `style` _[object]_ - 우편번호 검색창을 감싸는 최상위 엘리먼트에 적용할 스타일입니다. 기본값: `{ width: 100%, height: 400 }`
- `scriptUrl` _[string]_ - 컴포넌트에서 사용할 Daum 우편번호 스크립트 주소입니다. 기본값: `'https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js'`
- `defaultQuery` _[string]_ - 우편번호 검색창에 기본으로 입력할 검색어입니다. 기본값 : `undefined`
- `autoClose` _[boolean]_ - 우편번호 검색 완료시, 자동 닫힘 여부입니다. 주소를 선택하면, 최상위 엘리먼트를 돔에서 제거합니다. 기본값: `true`
- `errorMessage` _[React element]_ - Daum 우편번호 스크립트가 로드되지 않을 때 나타낼 에러 메시지입니다. 기본값: `<p>현재 Daum 우편번호 서비스를 이용할 수 없습니다. 잠시 후 다시 시도해주세요.</p>`
- 기타 Daum 우편번호 생성자 속성들을 동일한 이름으로 props를 전달할 수 있습니다. 속성값에 대해서는 [Daum 우편번호 서비스 가이드](http://postcode.map.daum.net/guide#attributes)를 참고해주세요.
`useDaumPostcodePopup` 실행 시 우편번호 서비스의 스크립트 주소를 전달할 수 있습니다. 반환한 함수를 실행할 때 다음 우편번호 서비스의 생성자 및 팝업 설정값을 전달할 수 있습니다. 전달하지 않은 설정값은 다음 우편번호 서비스의 기본 설정을 따라갑니다.

| name | type | default | description
|:----:|:----:|:-------:|:-----------|
| scriptUrl | `string` | [CURRENT_URL](https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js) | Daum 우편번호 서비스의 스크립트 주소입니다.|
| onComplete | `function` | `undefined` | 우편번호 검색이 끝났을 때 사용자가 선택한 정보를 받아올 콜백함수입니다. 주소 데이터의 구성은 [Daum 가이드](http://postcode.map.daum.net/guide)를 참고해주세요. |
| onSearch | `function` | `undefined` | 주소를 검색할 경우 실행되는 콜백함수입니다. 검색 결과 정보의 구성은 [Daum 가이드](http://postcode.map.daum.net/guide)를 참고해주세요. |
| onClose | `function` | `undefined` | 검색 결과를 선택하여, 서비스가 닫힐 때 실행되는 콜백함수입니다. |
| onResize | `function` | `undefined` | 검색 결과로 인해, 우편번호 서비스의 화면 크기가 변경될 때 호출되는 콜백함수입니다. 변경된 화면 정보의 구성은 [Daum 가이드](http://postcode.map.daum.net/guide)를 참고해주세요. |
| width | `string\|number` | `undefined` | 우편번호 검색창의 가로 너비입니다. |
| height | `string\|number` | `undefined` | 우편번호 검색창의 세로 높이입니다. |
| defaultQuery | `string` | `undefined` | 우편번호 검색창에 기본으로 입력할 검색어입니다. |
| top | `string\|number` | `undefined` | 팝업의 Y 위치를 나타내는 값입니다. |
| left | `string\|number` | `undefined` | 팝업의 X 위치를 나타내는 값입니다. |
| popupTitle | `string` | `undefined` | 팝업창의 상태표시줄에 나오는 Title 값을 지정할 수 있습니다. 전달하지 않을 경우, 다음 우편번호의 기본 설정 문구가 출력됩니다. |
| popupKey | `string` | `undefined` | 팝업창의 key 입니다. 전달하지 않을 경우 매번 새창이 열리게 됩니다. |
| autoClose | `boolean` | `true` | 우편번호 검색 완료시 자동 닫힘 여부입니다. 주소를 선택하면 팝업창이 닫힙니다.

기타 Daum 우편번호 생성자 속성들을 동일한 이름으로 props를 전달할 수 있습니다. 속성값에 대해서는 [Daum 우편번호 서비스 가이드](http://postcode.map.daum.net/guide#attributes)를 참고해주세요.


## 안내

`react-daum-postcode`는 Daum 우편번호 서비스와 독립적으로 제작된 패키지입니다. React환경에서 발생하는 `react-daum-postcode`의 버그는 패키지 레포지터리의 [이슈트래커](https://github.com/kimminsik-bernard/react-daum-postcode/issues)에 말씀해주세요. 만약 Daum 우편번호 서비스 자체의 문제라고 생각하신다면, 다음 우편번호 서비스의 [FAQ](https://github.com/daumPostcode/QnA/blob/master/README.md)와 [이슈트래커](https://github.com/daumPostcode/QnA/issues)를 참조해주세요.
`react-daum-postcode`는 Daum 우편번호 서비스와 독립적으로 제작된 패키지입니다. React환경에서 발생하는 `react-daum-postcode`의 버그는 패키지 레포지터리의 [이슈트래커](https://github.com/kimminsik-bernard/react-daum-postcode/issues)에 말씀해주세요. 만약 Daum 우편번호 서비스 자체의 문제라고 생각하신다면, 다음 우편번호 서비스의 [FAQ](https://github.com/daumPostcode/QnA/blob/master/README.md)와 [이슈트래커](https://github.com/daumPostcode/QnA/issues)를 참조해주세요.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "react-daum-postcode",
"version": "3.0.3",
"description": "React daum-postcode component",
"description": "Daum Postcode service for React",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"files": [
Expand Down Expand Up @@ -53,6 +53,7 @@
},
"keywords": [
"react",
"daum",
"postcode",
"zipcode"
],
Expand Down
35 changes: 15 additions & 20 deletions src/DaumPostcode.tsx → src/DaumPostcodeEmbed.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { Component, createRef, CSSProperties } from 'react';
import loadPostcode, { PostcodeConstructor, PostcodeOptions } from './loadPostcode';
import loadPostcode, { postcodeScriptUrl, PostcodeConstructor, PostcodeOptions } from './loadPostcode';

export interface DaumPostcodeProps extends Omit<PostcodeOptions, 'oncomplete' | 'onresize' | 'onclose' | 'onsearch'> {
export interface DaumPostcodeEmbedProps
extends Omit<PostcodeOptions, 'oncomplete' | 'onresize' | 'onclose' | 'onsearch' | 'width' | 'height'> {
onComplete?: PostcodeOptions['oncomplete'];
onResize?: PostcodeOptions['onresize'];
onClose?: PostcodeOptions['onclose'];
Expand All @@ -13,6 +14,13 @@ export interface DaumPostcodeProps extends Omit<PostcodeOptions, 'oncomplete' |
scriptUrl?: string;
autoClose?: boolean;
}
/**
* @deprecated
* type 'DaumPostcodeProps' is renamed to 'DaumPostcodeEmbedProps'.
* use 'DaumPostcodeEmbedProps' instead of 'DaumPostcodeProps'.
* it will be removed future version.
*/
export type DaumPostcodeProps = DaumPostcodeEmbedProps;

interface State {
hasError: boolean;
Expand All @@ -26,12 +34,12 @@ const defaultStyle = {
};

const defaultProps = {
scriptUrl: 'https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js',
scriptUrl: postcodeScriptUrl,
errorMessage: defaultErrorMessage,
autoClose: true,
};

class DaumPostcode extends Component<DaumPostcodeProps, State> {
class DaumPostcodeEmbed extends Component<DaumPostcodeEmbedProps, State> {
static defaultProps = defaultProps;

wrap = createRef<HTMLDivElement>();
Expand All @@ -50,21 +58,8 @@ class DaumPostcode extends Component<DaumPostcodeProps, State> {

initiate = (Postcode: PostcodeConstructor) => {
if (!this.wrap.current) return;
const {
scriptUrl,
className,
style,
defaultQuery,
autoClose,
errorMessage,
width,
height,
onComplete,
onClose,
onResize,
onSearch,
...options
} = this.props;
const { scriptUrl, className, style, defaultQuery, autoClose, errorMessage, onComplete, onClose, onResize, onSearch, ...options } =
this.props;

const postcode = new Postcode({
...options,
Expand Down Expand Up @@ -99,4 +94,4 @@ class DaumPostcode extends Component<DaumPostcodeProps, State> {
}
}

export default DaumPostcode;
export default DaumPostcodeEmbed;
11 changes: 6 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import DaumPostcode, { DaumPostcodeProps } from './DaumPostcode';
import { Address, Search, State } from './loadPostcode';
import DaumPostcodeEmbed, { DaumPostcodeEmbedProps, DaumPostcodeProps } from './DaumPostcodeEmbed';
import useDaumPostcodePopup, { DaumPostcodePopupParams } from './useDaumPostcodePopup';
import loadPostcode, { Address, Search, State } from './loadPostcode';

export type { DaumPostcodeProps, Address, Search, State };
export { DaumPostcode };
export default DaumPostcode;
export type { DaumPostcodeEmbedProps, DaumPostcodeProps, DaumPostcodePopupParams, Address, Search, State };
export { loadPostcode, DaumPostcodeEmbed, useDaumPostcodePopup };
export default DaumPostcodeEmbed;
10 changes: 7 additions & 3 deletions src/loadPostcode.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
declare global {
interface Window {
daum?: {
postcode?: {
postcode: {
load: (fn: () => void) => void;
version: string;
_validParam_: boolean;
};
Postcode?: PostcodeConstructor;
Postcode: PostcodeConstructor;
};
}
}
Expand Down Expand Up @@ -84,6 +84,8 @@ export interface PostcodeOptions {
focusInput?: boolean;
focusContent?: boolean;
autoMapping?: boolean;
autoMappingRoad?: boolean;
autoMappingJibun?: boolean;
shorthand?: boolean;
pleaseReadGuide?: number;
pleaseReadGuideTimer?: number;
Expand Down Expand Up @@ -121,11 +123,13 @@ export interface Postcode {
embed(element: HTMLElement, embedOptions?: EmbedOptions): void;
}

export const postcodeScriptUrl = 'https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js';

const loadPostcode = (function () {
const scriptId = 'daum_postcode_script';
let promise: Promise<PostcodeConstructor> | null = null;

return function (url: string): Promise<PostcodeConstructor> {
return function (url: string = postcodeScriptUrl): Promise<PostcodeConstructor> {
if( promise ) return promise;

promise = new Promise((resolve, reject) => {
Expand Down
45 changes: 45 additions & 0 deletions src/useDaumPostcodePopup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useCallback, useEffect } from 'react';

import loadPostcode, { PostcodeOptions, OpenOptions, postcodeScriptUrl } from './loadPostcode';

export type DaumPostcodePopupParams = Omit<PostcodeOptions, 'oncomplete' | 'onresize' | 'onclose' | 'onsearch'> &
Omit<OpenOptions, 'q'> & {
onComplete?: PostcodeOptions['oncomplete'];
onResize?: PostcodeOptions['onresize'];
onClose?: PostcodeOptions['onclose'];
onSearch?: PostcodeOptions['onsearch'];
onError?: (error: Error) => void;
defaultQuery?: string;
};

function useDaumPostcodePopup(scriptUrl = postcodeScriptUrl) {
useEffect(() => {
loadPostcode(scriptUrl);
}, [scriptUrl]);

const open = useCallback(
(options?: DaumPostcodePopupParams) => {
const { defaultQuery, left, top, popupKey, popupTitle, autoClose, onComplete, onResize, onClose, onSearch, onError, ...others } = {
...options,
};

return loadPostcode(scriptUrl)
.then((Postcode) => {
const postcode = new Postcode({
...others,
oncomplete: onComplete,
onsearch: onSearch,
onresize: onResize,
onclose: onClose,
});
postcode.open({ q: defaultQuery, left, top, popupTitle, popupKey, autoClose });
})
.catch(onError);
},
[scriptUrl]
);

return open;
}

export default useDaumPostcodePopup;