사용자가 도시 이름을 입력할 때, 정확한 도시 이름을 입력값으로 받아오기 위해 도시 자동완성을 구현하고자 했다.
그리고 react-google-autocomplete
라는 라이브러리를 찾았다.
깃헙 document
npm i react-google-autocomplete --save
or
yarn add react-google-autocomplete
사용자 인증 정보 만들기
를 클릭하여 API키를 만든다.전체적인 코드 구조는 깃헙 document의 Example를 참고했고, 나머지는 내 프로젝트에 맞게 커스텀했다.
useGoogle hook
은 google place autocomplete service
를 이용하고, 이 서비스로 이용 가능한 기능을 return 해준다. 또한 input 값으로 구글에 요청을 보내는 수를 줄일 수 있는 debounce prop
을 설정할 수 있다.
현재는 debounce 기능을 lodash 라이브러리를 통해 구현하고 있다고 한다.
import React, { useState } from 'react'
import { List } from "antd";
import useGoogle from "react-google-autocomplete/lib/usePlacesAutocompleteService";
type Props = {
place: string,
setPlace: React.Dispatch<React.SetStateAction<string>>
}
const AutoComplete = ({ place, setPlace }: Props) => {
const {
placePredictions,
getPlacePredictions,
isPlacePredictionsLoading,
} = useGoogle({
apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
});
const [chosen, setChosen] = useState("")
return (
<div className="relative flex flex-col w-full">
<span>여행지</span>
<input
className="w-full p-2 my-2 border rounded"
value={place}
placeholder="여행지 입력"
onChange={(evt: any) => {
getPlacePredictions({ input: evt.target.value });
setChosen(evt.target.value);
setPlace(evt.target.value);
}}
/>
{chosen && <div className="absolute h-[10rem] left-0 overflow-x-hidden flex whitespace-nowrap flex-col w-full my-1 bg-white border z-[9999] rounded top-20">
{!isPlacePredictionsLoading && (
<List className="px-2"
dataSource={placePredictions}
renderItem={(item: any) => (
<List.Item className="cursor-pointer" onClick={() => {
setChosen("")
setPlace(item.description)
}
}>
<List.Item.Meta title={item.description} />
</List.Item>
)}
/>
)}
</div>}
</div>
);
}
export default AutoComplete