본문 바로가기
TIL

[TIL] 2023.05.19 react-phone-input-2로 국가 번호 입력 dropdown 구현하기

by heereal 2023. 5. 19.

해외 전화번호를 입력할 때 국가 코드를 dropdown 형태로 선택할 수 있게 구현하고 싶었다. 검색 결과 react-phone-input-2라는 리액트를 위한 라이브러리가 있어서 공식문서도 잘 정리되어 있고 UI도 프로젝트와 잘 어울려서 사용하기로 결정했다.

 

import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/style.css';

<PhoneInput
    country={'kr'} // initial country
    preferredCountries={['us', 'cn', 'jp', 'kr']} // country codes to be at the top
    enableSearch={true}
    inputProps={{ name: 'phone', required: true }}
    inputStyle={{ width: '40rem', height: '5rem', fontSize: '1.5rem' }}
/>

npm 설치 후 PhoneInput 컴포넌트를 import 해서 사용하면 된다. 드롭다운에 특정 국가들만 상단에 고정해서 보여주는 기능도 preferredCountries라는 옵션을 이용해서 매우 간단하게 구현할 수 있어 마음에 들었다. enableSearch 옵션을 true로 설정하면 드롭다운에 검색창까지 생성된다.

 

이렇게 옵션이 상세하고 내가 원하는 대로 커스텀 가능한 라이브러리를 오랜만에 만나서 기능 구현도 금방 끝내고 뿌듯했다. ㅎㅎ 그 외에 원하는 옵션이나 스타일 지정이 필요하다면 하단에 npm 링크 참고하기!

 

 

공식문서

 

react-phone-input-2

A react component to format phone numbers. Latest version: 2.15.1, last published: a year ago. Start using react-phone-input-2 in your project by running `npm i react-phone-input-2`. There are 298 other projects in the npm registry using react-phone-input-

www.npmjs.com

 

 

 

 

댓글