import { useEffect } from 'react'; import { CSSProperties, useRef, useState } from 'react'; import PlacesAutocomplete, { Suggestion } from 'react-places-autocomplete'; import getPlaceDetails from '../../lib/getPlaceDetails'; type Opts = Parameters['0']; const style: CSSProperties = { marginTop: '-1em', paddingTop: '2em', paddingBottom: '1em', paddingLeft: '1em', paddingRight: '1em', borderBottomLeftRadius: '0.5em', borderBottomRightRadius: '0.5em', backgroundColor: 'white', maxWidth: '100%', textAlign: 'left', }; function SuggestionsList({ suggestions, getSuggestionItemProps, }: { suggestions: readonly Suggestion[]; getSuggestionItemProps: Opts['getSuggestionItemProps']; }) { return (
{suggestions.map((suggestion) => (
{suggestion.description}
))}
); } export default function UIPlacesAutocomplete({ onSelected, placeholder = 'Enter a location', disabled = false, style, placeId, }: { onSelected?: (address: string, placeID: string) => void; placeholder?: string; disabled?: boolean; style?: CSSProperties; placeId?: string | null; }) { const [location, setLocation] = useState(''); const suggestionsRef = useRef([]); useEffect(() => { if (placeId) { getPlaceDetails(placeId) .then((result) => { if (result.formattedAddress.startsWith(result.name)) { setLocation(result.formattedAddress); } else { setLocation(`${result.name}, ${result.formattedAddress}`); } }) .catch(console.error); // TODO error handling } }, [placeId]); return ( { setLocation(location); if (onSelected) { onSelected(null!, null!); } }} onSelect={(address, placeID) => { setLocation(address); if (onSelected) { onSelected(address, placeID); } }} value={location} > {({ getInputProps, getSuggestionItemProps, suggestions, loading }) => { if (!loading) { suggestionsRef.current = suggestions; } return (
{suggestionsRef.current.length > 0 && ( )}
); }}
); }