2

I have a search bar with the Google Maps Places Autocomplete.
I am using the npm package 'react-places-autocomplete' in Next.js.

To get only suggestions of residential address and cities of a specific country,
I add an object to searchOptions with two keys: 'componentRestrictions' and 'types'.
In the key 'types' I need to add two values 'address' and '(cities)'
(like from the documentation of google places in https://developers.google.com/places/web-service/autocomplete#place_types).

My code:

import React, { useState } from 'react';
import Head from 'next/head';
import PlacesAutocomplete from 'react-places-autocomplete';

export default function Search() {

  const [state,setState] = useState({address:'',errorMessage:''})

  const handleChange = (address) =>{
    setState({address,errorMessage:''})
  } 

  return (
    <>
      <Head>
        <script src="https://maps.googleapis.com/maps/api/js?key=MyApiKey&libraries=places"></script>
      </Head>

      <div className={styles.searchBar}>

        <PlacesAutocomplete
          value={state.address}
          onChange={handleChange}
          searchOptions={{componentRestrictions: { country: ['fr'] }, types: ['address','(cities)']}}
        >
          {renderFunc}
        </PlacesAutocomplete>

      </div>
    </>
  )

  const renderFunc = ({ getInputProps, getSuggestionItemProps, suggestions, loading }) => (
    <div>
      <input className={styles.inputSearchBar}  {...getInputProps()} />
      <div >
        {loading && <div>Loading...</div>}
        {suggestions.map(suggestion => {
          const className = suggestion.active ? 'suggestion-item--active' : 'suggestion-item';
          const style = suggestion.active
                  ? { backgroundColor: 'red', cursor: 'pointer',border: '1px solid' }
                  : { backgroundColor: '#ffffff', cursor: 'pointer',border: '1px solid' };
          return (<div {...getSuggestionItemProps(suggestion,{className,style})}>
            <span>{suggestion.description}</span> 
          </div>
          )
        })}
      </div>
    </div>
  );

I get these two errors:

index.js:1 Warning: Failed prop type: The prop value is marked as required in PlacesAutocomplete, but its value is undefined.

index.js:1 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

But if I put only one type in searchOptions like this it works

<PlacesAutocomplete
          value={state.address}
          onChange={handleChange}
          searchOptions={{componentRestrictions: { country: ['fr'] }, types: ['address']}}
        >

Thus, how is it possible to have two types 'address' and '(cities)'?

sam
  • 95
  • 1
  • 2
  • 10

0 Answers0