'reactjs-select + react-google-places-autocomplete: how to initialize with a place
I am using a ready made component from https://www.npmjs.com/package/react-google-places-autocomplete for google autocomplete places
But I want to initialize it with place. (because when i edit a form, i have to show the place there)
import React from "react";
import GooglePlacesAutocomplete from "react-google-places-autocomplete";
const GooglePlacesAutocompleteComponent = () => (
<div>
<GooglePlacesAutocomplete
apiKey="xxxxxxxxxxxxxxx"
/>
</div>
);
export default Component;
The above is the component
and use is as
<GooglePlacesAutocompleteComponent />}
I know react-google-places-autocomplete uses react-select AsyncSelect
<AsyncSelect
{...selectProps}
loadOptions={fetchSuggestions}
getOptionValue={({ value }) => value.place_id}
/>
the fetchsugestions is list of {label and value}
HOw to pass the intial value
Solution 1:[1]
This is best achieved following the docs of React-Select as suggested by the creator. But to achieve what you want to do, you'll need React State.
import { useState, useEffect } from "react"
import GooglePlacesAutocomplete from "react-google-places-autocomplete"
const Places = () => {
const [data, setData] = useState("");
//our default data
useEffect(() => {
data === "" ? setData("") : setData(data.label);
}, [data]);
// updating our default data
return (
<GooglePlacesAutocomplete
apiKey={process.env.REACT_APP_MAP_API_KEY}
autocompletionRequest={{
componentRestrictions: {
country: ["ng"] //to set the specific country
}
}}
selectProps={{
defaultInputValue: data, //set default value
onChange: setData, //save the value gotten from google
placeholder: "Start Destination",
styles: {
input: (provided) => ({
...provided,
color: "#222222"
}),
option: (provided) => ({
...provided,
color: "#222222"
}),
singleValue: (provided) => ({
...provided,
color: "#222222"
})
}
}}
onLoadFailed={(error) => {
console.log(error);
}}
/>
)
}
export default Places;
We use useEffect to update the defualt value we set on condition that we are getting an actual value. If we're not getting actual value, we're not saving it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | blaumeise20 |
