React-native-google-places-autocomplete: not hide after onpress (setState) and onclick another input its trigger ?

Created on 5 Sep 2018  路  6Comments  路  Source: FaridSafi/react-native-google-places-autocomplete

I have multiple iput form datepicker and now problem is that i made component Googleplace

import React from 'react';
import {PLACE_API} from '../../config/env'
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";


export default class GooglePlaces extends React.Component {

  render() {
    console.log(this.state);
    return (
      <GooglePlacesAutocomplete
        placeholder={this.props.placeHolder ? this.props.placeHolder : 'Search'}
        minLength={2} // minimum length of text to search
        autoFocus={false}
        fetchDetails={true}
        onPress={(data, details = null) => this.props.onSelectAddress(details)}
        getDefaultValue={() => {
          return this.props.defaultText ? this.props.defaultText : ''; // text input default value
        }}
        query={{
          // available options: https://developers.google.com/places/web-service/autocomplete
          key: PLACE_API,
          language: 'en', // language of the results
          types: '(cities)', // default: 'geocode'
        }}
        styles={{
          description: {
            fontWeight: 'bold',
          },
          predefinedPlacesDescription: {
            color: '#1faadb',
          },
        }}

        // text=''

        currentLocation={false} // Will add a 'Current location' button at the top of the predefined places list
        currentLocationLabel="Current location"
        nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
        GoogleReverseGeocodingQuery={{
          // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
        }}

      />
    )
  }
}

and here is my component

```

import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, TextInput, ScrollView, Alert } from 'react-native';

import GooglePlaces from '../../../Common/GooglePlaces';
import styles from '../../../../assets/css/style'
import {PLACE_API} from '../../../../config/env'
import moment from 'moment'
import DateTimePicker from 'react-native-modal-datetime-picker'
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";

export default class AddTripInternational extends React.Component {
constructor(props) {
super(props);
this.state = {
isDateTimePickerVisible: false,
isNotification: true,
travel_date: '',

        address_from: '',
        country_from: '',
        country_code: '',
        lang_from: null,
        lat_from: null,

        address_to: '',
        country_to: '',
        lang_to: null,
        lat_to: null
    }

    this._handleFrom    = this._handleFrom.bind(this);
    this._handleTo      = this._handleTo.bind(this);
    this._issamecountry = this._issamecountry.bind(this);
}

handlerSwitchToggle = () => {
    this.setState({
        isNotification: !this.state.isNotification
    })
}

_showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true })

_hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false })

_handleDatePicked = async (date) => {
    await this.setState({
        travel_date: moment(date).format('DD/MM/YYYY')
    })
    this._hideDateTimePicker();
}

async _issamecountry(forplace) {


    try {
        if (forplace) {
            // await this.setState({
            //     address_from: ''
            // })
        }else{
            // await this.setState({
            //     address_to: ''
            // })
        }

        await Alert.alert('Hey :) Please choose the two different countries')
    } catch (error) {
        console.log(error);

    }
}


async _handleFrom (data) {


    // try {
    //     await this.setState({
    //         // address_from: data.formatted_address,
    //         // country_from: data.address_components[data.address_components.length -1].long_name,
    //         // country_code: data.address_components[data.address_components.length -1].short_name,
    //         // lang_from: data.geometry.location.lng,
    //         // lat_from: data.geometry.location.lat
    //     })

    //     if (this.state.country_from  === this.state.country_to) {
    //         await this._issamecountry(1)
    //     }

    // } catch (error) {
    //    console.log(error);
    // }
}

async _handleTo (data) {


    // try {
    //     await this.setState({
    //         address_to: data.formatted_address,
    //         country_to: data.address_components[data.address_components.length -1].long_name,
    //         lang_to: data.geometry.location.lng,
    //         lat_to: data.geometry.location.lat
    //     })

    //     if (this.state.country_from === this.state.country_to) {
    //         await this._issamecountry(0)
    //     }
    // } catch (error) {
    //     console.log(error)
    // }
}


render() {
    const pagestyle = StyleSheet.create({
        toggel: {
            height: 25,
            width: 28,
            borderRadius: 50,
            backgroundColor: '#fff',
        },
        toggelnotify: {
            left: this.state.isNotification ? 30 : 0,

        },
        switch: {
            height: 25,
            width: 60,
            borderRadius: 50,
        },
        switchnotify: {
            backgroundColor: this.state.isNotification ? '#660165' : '#ccc',
        },

    })

    return (
        <View style={[styles.addTripbox, styles.shadow]}>

             <GooglePlaces onSelectAddress={this._handleFrom}  placeHolder="From city/country"/> 
           <GooglePlaces onSelectAddress={this._handleTo}  placeHolder="To city/country"/> 

            <View style={styles.fromgroup}>
                <TouchableOpacity onPress={() => this._showDateTimePicker()}>
                    <TextInput style={styles.inputbox}
                        placeholder="DD/MM/YYY"
                        placeholderTextColor="#878787"
                        underlineColorAndroid='rgba(0, 0, 0,0)'
                        editable={false}
                        value={this.state.travel_date}
                    />
                </TouchableOpacity>
            </View>

            <DateTimePicker
                isVisible={this.state.isDateTimePickerVisible}
                onConfirm={this._handleDatePicked}
                onCancel={this._hideDateTimePicker}
                minimumDate={new Date()}
            />



        </View>

    );
}

}

after onpress list not hide and after i and even I click on another input my autocomplete trigger

Most helpful comment

Just faced the same issue, looks like the behavior has changed.
It looks like you need to use listViewDisplayed = false.

<GooglePlacesAutocomplete
  // other props
  listViewDisplayed={ false } />

All 6 comments

Just faced the same issue, looks like the behavior has changed.
It looks like you need to use listViewDisplayed = false.

<GooglePlacesAutocomplete
  // other props
  listViewDisplayed={ false } />

@alexsegura i added that..it's not working. It still doesn't close

@alexsegura Be careful with this trick. It can cause unwanted side effects

See my comment on https://github.com/FaridSafi/react-native-google-places-autocomplete/issues/133

@alexsegura
if we use

<GooglePlacesAutocomplete
  // other props
  listViewDisplayed={ false } />

listview will be invisible after press any item, that fine ok... but the pressed value is not selecting(not filling TextInput Field)...

i found solution for my issue here https://github.com/FaridSafi/react-native-google-places-autocomplete/issues/230#issuecomment-387136217

Try my method address_components to re-usable object :)

https://gist.github.com/joeljerushan/43782c172d9bf5690cdbc5362b8fc0c5

```getPlaceInfo() {
//setting address_components from GooglePlacesAutocomplete Return
let place = this.state.address_components

//creating object for namespaces from GooglePlacesAutocomplete
var place_info = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name',
administrative_area_level_2: 'short_name',
neighborhood: 'long_name',
};

//create readable object
var address_list = {}

//the loop
for(let i = 0; i < place.length; i++) {

//getting namespaces from GooglePlacesAutocomplete return data
var addressType = place[i].types[0];

//matching namespaces from local namespace object(place_info)
if (place_info[addressType]) { 

  //add and find GooglePlacesAutocomplete return namespace to a var
  var val = place[i][place_info[addressType]];

  //add key and value to object
  address_list[addressType] = val 
}

}

//whatever you want do it here with that object ;)
this.setState({ address_readable: address_list })

}

What i did to fix this was convert the component to a stateful one, then passed a function to it as a prop to set the state of the parent component onPress. Then in the shouldComponentUpdate of the GoogleAutoComplete, simple return false , here's the code

``
export class GooglePlacesInput extends Component {

shouldComponentUpdate() {
    return false;
}

render() {
    const { placeholder, label, name, handlePlacesChange } = this.props

    return (
        <Content style={Styles.margin(5)}>
            <Label style={[Styles.margin(18, 'left'), Styles.color(mainColor)]}>{label}</Label>
            <GooglePlacesAutocomplete
                placeholder={placeholder}
                renderDescription={row => row.description}
                textInputProps={{
                    onChangeText: (text) => handlePlacesChange(text, name)
                }}
                onPress={(data) => {
                    handlePlacesChange(data.description, name)
                }}
                query={{
                    key: 'AIzaSyAZnJjBtjxouw0lfQJYGKl3l68n24LGOKA',
                    language: 'en',
                    types: 'address',
                    components: 'country:ng'

                }}
                styles={{
                    textInputContainer: {
                        backgroundColor: 'transparent',
                        borderTopWidth: 0,
                        borderBottomWidth: 0,
                    },
                    textInput: {
                        height: 38,
                        color: '#5d5d5d',
                        fontSize: 16,
                        borderBottomWidth: 3,
                        borderBottomColor: 'silver',
                    },
                    predefinedPlacesDescription: {
                        color: '#1faadb'
                    }
                }}
                GooglePlacesDetailsQuery={{
                    fields: 'formatted_address',
                }}
            />
        </Content>
    );
}

}``

Was this page helpful?
0 / 5 - 0 ratings