React-native-google-places-autocomplete: Not working with KeyboardAwareScrollView

Created on 18 Dec 2019  路  12Comments  路  Source: FaridSafi/react-native-google-places-autocomplete

I'm currently using KeyboardAwareScrollView with react-native-google-places-autocomplete and only when the auto-complete component is within KeyboardAwareScrollView, the drop-down suggested addresses from Google does not respond to presses. When the aut0-complete component is without KeyboardAwareScrollView, the component works as expected.

The expected behavior is that when the suggested addresses are clicked, the clicked addresses can be used in the onPress property of react-native-google-places-autocomplete, but when the component is placed within KeyboardAwareScrollView, the suggested list disappears as soon as the list is clicked, and no addresses are selected or retrieved.

const CreatePost = ({ navigation }) => {
    const [animation] = useState(new Animated.Value(0))
    useEffect(() => {
        Keyboard.addListener('keyboardWillShow', keyboardWillShow)
        Keyboard.addListener('keyboardWillHide', keyboardWillHide)
        return () => {
            Keyboard.removeListener()
        }
    }, [])

    const keyboardWillShow = e => {
        Animated.timing(animation, {
            duration: e.duration,
            toValue: 1,
        }).start()
    }

    const keyboardWillHide = e => {
        Animated.timing(animation, {
            duration: e.duration,
            toValue: 0,
        }).start()
    }

    const opacityInterpolate = animation.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 0]
    })

    const photoStyles = {
        opacity: opacityInterpolate
    }

    const submitHandler = async (value, action) => {}

    return (
        <KeyboardAwareScrollView>
            <Form submitHandler={submitHandler} />
        </KeyboardAwareScrollView>

    )
}

I placed react-native-google-places-autocomplete within Formik:

const Form = ({
    submitHandler,
}) => {
const [addressAnimation] = useState(new Animated.Value(0))
const [addressHeight, setAddressHeight] = useState()
const yCoordinate = heightPosition - addressHeight

const onFocusAddressAutoComplete = () => {
    // onFocus Animation
}
const onBlurAddressAutoComplete = () => {
    // onBlur Animation
}

const translateInterpolate = addressAnimation.interpolate({
    inputRange: [0, 1],
    outputRange: [0, !!yCoordinate && yCoordinate],
    extrapolate: "clamp",
})

const addressStyle = {
    transform: [
        {
            translateY: translateInterpolate
        }
    ]
}

const onFocusProps = () => {
    setHideList(true)
    onFocusAddressAutoComplete()
}

const onBlurProps = (param, callback) => {
    callback(param)
    onBlurAddressAutoComplete()
    setHideList(false)
}

return (
    <View style={styles.container} >
        <Formik
            initialValues={initialValues}
            onSubmit={(value, action) => submitHandler(value, action)}
            validationSchema={yup.object().shape({
                address: yup
                    .string()
                    .min(5)
                    .required(),
            })}
        >
            {({
                values,
                handleChange,
                errors,
                setFieldTouched,
                touched,
                isValid,
                handleSubmit,
                resetForm,
                isSubmitting,
                }) => (
                    <View style={styles.form}>
                        <Animated.View
                            style={[styles.fieldset, addressStyle]}
                            onLayout={e => {
                                if (addressHeight !== e.nativeEvent.layout.y) {
                                    setAddressHeight(e.nativeEvent.layout.y)
                                }
                            }}
                        >
                            <Text style={{ marginLeft: 40, marginVertical: 5 }}>
                                <Text style={{ color: '#FF5D4E' }}>* </Text>
                                Address
                                </Text>
                            <View style={styles.autoComplete}>
                                <GooglePlacesInput
                                    onBlur={() => onBlurProps('address', setFieldTouched)}
                                    onChangeText={handleChange('address')}
                                    onFocus={onFocusProps}
                                />
                            </View>
                        </Animated.View>
                        {touched.address && errors.address &&
                            <Animated.Text style={{ fontSize: 10, color: 'red' }}>{errors.address}</Animated.Text>
                        }
                        <TouchableOpacity
                            disabled={!isValid || loading || isSubmitting}
                            onPress={handleSubmit}
                            style={styles.button}
                        >
                            <Text style={styles.buttonText}>Submit</Text>
                        </TouchableOpacity>
                    </View>
                )}
        </Formik>
    </View>
    )
}

Standard GooglePlacesAutocomple from the repository:


<GooglePlacesAutocomplete
    placeholder='Search'
    minLength={2} // minimum length of text to search
    autoFocus={false}
    returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
    keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
    listViewDisplayed={false}   // true/false/undefined
    fetchDetails={true}
    renderDescription={row => row.description} // custom description render
    onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
        console.log(data, details);
    }}
    textInputProps={ }}
    getDefaultValue={() => ''}

    query={{
        // available options: https://developers.google.com/places/web-service/autocomplete
        key: googleAPIKeyForAutocomplete,
        language: 'en', // language of the results
        region: "CA",
        // types: '(cities)' // default: 'geocode'
        types: '',
    }}


    currentLocation={true} // 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
    }}
    GooglePlacesSearchQuery={{
        // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
        rankby: 'distance',
        type: 'food'
    }}

    GooglePlacesDetailsQuery={{
        // available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
        fields: 'formatted_address',
    }}

    filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
    predefinedPlaces={[]}
    enablePoweredByContainer={false}
    debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
    renderLeftButton={() => { }}
    renderRightButton={() => { }}
/>
bug

Most helpful comment

@igibliss00 Have you tried to add keyboardShouldPersistTaps in all ancestor ScrollView?

<ScrollView keyboardShouldPersistTaps={'handled'}>
     <ScrollView keyboardShouldPersistTaps={'handled'}>
            <GooglePlacesAutocomplete ... >

All 12 comments

did you find any solution ?

yes because of this module is using scroll view into flatlist.
so i found a solution to creating a new custom autocomplete list :D

yes because of this module is using scroll view into flatlist.
so i found a solution to creating a new custom autocomplete list :D

How did you create it?

yes because of this module is using scroll view into flatlist.
so i found a solution to creating a new custom autocomplete list :D

I was able to resolve this issue by ensuring that i had no other ScrollView's or FlatList's within the KeyboardAwareScrollView. Now all is working as expected.

still encountering this issue

@igibliss00 Have you tried to add keyboardShouldPersistTaps in all ancestor ScrollView?

<ScrollView keyboardShouldPersistTaps={'handled'}>
     <ScrollView keyboardShouldPersistTaps={'handled'}>
            <GooglePlacesAutocomplete ... >

@igibliss00 Have you tried to add keyboardShouldPersistTaps in all ancestor ScrollView?

<ScrollView keyboardShouldPersistTaps={'handled'}>
     <ScrollView keyboardShouldPersistTaps={'handled'}>
            <GooglePlacesAutocomplete ... >

this works in my case

Closing, as this is now documented in the readme. Thanks @FabrizioCaldarelli!

I still see the warning when I click the suggested places, and I have added keyboardShouldPersistTaps={'handled'} to the <ScrollView/>

It's still not working on android. I too have addedkeyboardShouldPersistTaps={'handled'} on the parent <ScrollView>component.

For me it works on Android with keyboardShouldPersistTaps={'handled'} but on ios onPress() is never called.
This happened if use it inside: https://github.com/abbasmoosavi/react-native-best-viewpager
This fix issue for ios its strange that the same work on Android without keyboardShouldPersistTaps <IndicatorViewPager keyboardShouldPersistTaps={'handled'}

did you find any solution ?

customized GooglePlaceAutoComplete.js replace touchable highlight with TouchableOpacity and works fine for me

Was this page helpful?
0 / 5 - 0 ratings

Related issues

akhlopyk picture akhlopyk  路  3Comments

GervaisYO picture GervaisYO  路  4Comments

macs03 picture macs03  路  3Comments

biks152207 picture biks152207  路  4Comments

lukBakTsh picture lukBakTsh  路  3Comments