| 1 |
import { TextControl } from '@wordpress/components'; |
| 2 |
import { useEffect, useRef, useState } from '@wordpress/element'; |
| 3 |
|
| 4 |
/* |
| 5 |
* Search Box Component. |
| 6 |
*/ |
| 7 |
export default function SearchBox(props) { |
| 8 |
const { label, placeholder, className, onChange } = props; |
| 9 |
|
| 10 |
const inputRef = useRef(null); |
| 11 |
const [value, setValue] = useState(''); |
| 12 |
|
| 13 |
useEffect(() => { |
| 14 |
if (!inputRef?.current || !window?.google?.maps?.places) { |
| 15 |
return; |
| 16 |
} |
| 17 |
|
| 18 |
const searchBox = new window.google.maps.places.SearchBox( |
| 19 |
inputRef.current |
| 20 |
); |
| 21 |
|
| 22 |
searchBox.addListener('places_changed', () => { |
| 23 |
const places = searchBox.getPlaces(); |
| 24 |
|
| 25 |
if (onChange) { |
| 26 |
onChange(places); |
| 27 |
|
| 28 |
if (places && places[0]) { |
| 29 |
setValue(places[0].formatted_address); |
| 30 |
} |
| 31 |
} |
| 32 |
}); |
| 33 |
}, [inputRef, onChange]); |
| 34 |
|
| 35 |
return ( |
| 36 |
<div className={className}> |
| 37 |
<TextControl |
| 38 |
ref={inputRef} |
| 39 |
label={label} |
| 40 |
placeholder={placeholder} |
| 41 |
value={value} |
| 42 |
onChange={(val) => { |
| 43 |
setValue(val); |
| 44 |
}} |
| 45 |
/> |
| 46 |
</div> |
| 47 |
); |
| 48 |
} |
| 49 |
|