React-native-google-places-autocomplete: Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Created on 19 Aug 2016  路  14Comments  路  Source: FaridSafi/react-native-google-places-autocomplete

I am getting this error:-
Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

This is my code:--

// @flow
'use strict';

import React, { Component } from 'react';
import {
View
} from 'react-native';
import GooglePlacesAutocomplete from 'react-native-google-places-autocomplete';
import { Actions } from 'react-native-router-flux';

// Styles
import * as googlePlacesStyle from '../googleplaces/style';

export default class GooglePlacesScene extends Component {

  state: {
    homePlace?: {
        description: string,
        geometry: {
            location: {
                lat: number,
                lng: number
            }
        }
    },
    workPlace?: {
        description: string,
        geometry: {
            location: {
                lat: number,
                lng: number
            }
        }
    }
};

constructor(props: {}) {
    super(props);

    this.state = {  homePlace: { description: 'Home', geometry: { location: { lat: 48.8152937, lng: 2.4597668 }}},
                    workPlace: {description: 'Work', geometry: { location: { lat: 48.8496818, lng: 2.2940881 } }}};
}

render() {
    return(
     <View style={googlePlacesStyle.bodyStyle}>
         <GooglePlacesAutocomplete
            placeholder='Search'
            minLength={2}
            autoFocus={false}
            fetchDetails={true}
            onPress={(data, details = null) => {
                console.log(data);
                console.log(details);
            }}
            getDefaultValue={() => {
                return ''; // text input default value
            }}
            query={{
                key: 'ALaiPuRiT3eyqE9CDhjjklAD2179Pw1uRoeVfBq',
                language: 'en',
                types: '(cities)',
            }}
            styles={{description: {
                fontWeight: 'bold',
            },
            predefinedPlacesDescription: {
                color: '#1faadb',
            },
        }}
        currentLocation={true}
        currentLocationLabel="Current location"
        nearbyPlacesAPI='GooglePlacesSearch'
        GoogleReverseGeocodingQuery={{
        }}
        GooglePlacesSearchQuery={{
            rankby: 'distance',
            types: 'food',
        }}
        filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']}
        predefinedPlaces={[this.state.homePlace, this.state.workPlace]}
       />

    </View>
    );
}

}

Most helpful comment

@GuelorEmanuel

Look at the way you import the component:

import GooglePlacesAutocomplete from 'react-native-google-places-autocomplete';

It should be imported like this

import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

All 14 comments

experiencing the same issue on react-native 0.31.0

getting the same on react native 0.23

Hi @davidgruebl @janroures @GuelorEmanuel

Thanks for your feedback. I promise to look at it this weekend.

Max

@myaskevich in my case it only happens when tapping a list element.

I just looked at it and here's what I got:

The version 1.2+ of this library requires RN v0.28+. Please check your dependencies once again @davidgruebl . Best way to check RN version is to run RN cli command - react-native --version.

@myaskevich
Just checked my version and it's

react-native-cli: 1.0.0
react-native: 0.31.0

@GuelorEmanuel

Look at the way you import the component:

import GooglePlacesAutocomplete from 'react-native-google-places-autocomplete';

It should be imported like this

import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

@myaskevich
That actually worked, thanks a lot! If you don't mind can you explain the different between the two syntax, why do we need to wrap the name in curly braces?

This is a new ES6 feature called destructing. You can read up on this here. See example:

// module1.js
export const foo = () => {
  console.log('foo');
};
export const bar = () => {
  console.log('bar');
};

// module2.js

// option 1
import module1 from 'module1';
module1.foo() // prints 'foo';

// option2
import { foo } from 'module1';
foo() // prints 'foo';

In order to support the way of importing you proposed, one has to use export default keyword. See below:

// module1.js
export default const foo = () => {
  console.log('foo');
};

// module2.js
import foo from 'module1';

foo(); // prints 'foo'

The reason why we need to do it for now is that because the original library author has put it like this in the first place. I'll probably change it in the future to support that direct import of the component.

That didn't work for me. Using RN 0.23 and 1.1.9 of this library.

Here is my code:

'use strict';

var React = require('react-native');

import Dimensions from 'Dimensions';

import { eventEmitter } from '../utils/EventEmitter';
import {GOOGLE_GEO_APIKEY} from "../config/constants";
import {GooglePlacesAutocomplete} from 'react-native-google-places-autocomplete';

import I18n from 'react-native-i18n';

var {height, width} = Dimensions.get('window');
var pinX = (width/2) - 22.5;
var MapView = require('react-native-maps');
var {
    InteractionManager,
    AsyncStorage,
    TextInput,
    Image,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    ListView,
} = React;

export class SecuritySignupLocationMap extends React.Component {

    constructor() {
        super();
        this.state = Store.getState();
        this.state.region = null;
        this.onListTap.bind(this);

        this.pinY = 0;
    }

    componentWillMount() {
        this.locationSelectedEvent = eventEmitter.addListener('locationSelectedEvent', this.save.bind(this));
        this.locationSelectedEventSignup = eventEmitter.addListener('locationSelectedEventSignup', this.saveSignup.bind(this));

        if (this.props.type == "signup") {
            this.pinY = (height/2) - 67.5;
        }else{
            this.pinY = (height/2) - 107.5;
        }
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            this.setState({
                region: {
                    latitude: this.props.latitude,
                    longitude: this.props.longitude,
                    latitudeDelta: 0.005,
                    longitudeDelta: 0.0041
                }
            });
        });
    }

    componentWillUnmount() {
        this.locationSelectedEvent.remove();
        this.locationSelectedEventSignup.remove();
    }

    onRegionChangeComplete(region) {
        this.setState({
            region: region
        });
    }

    save() {
        var location = {
            latitude: this.state.region.latitude,
            longitude: this.state.region.longitude
        }
        Actions.fetchAddressForLocation(location);
        NavActions.back();
    }

    saveSignup() {
        var location = {
            latitude: this.state.region.latitude,
            longitude: this.state.region.longitude
        }
        Actions.fetchAddressForLocation(location);
        Actions.back();

    }

    onListTap(location) {
        var longitude = location.geometry.location.lng;
        var latitude = location.geometry.location.lat;

        var region = {
            latitude: latitude,
            longitude: longitude,
            latitudeDelta: this.state.region.latitudeDelta,
            longitudeDelta: this.state.region.longitudeDelta
        };

        this.refs.map.animateToRegion(region);
        this.state.region = region;
    }

    render() {
        if (this.state.region) {
            return (
              <View ref='view'>
                <MapView
                ref='map'
                    style={styles.map}
                    initialRegion={{
                    latitude: this.state.region.latitude,
                    longitude: this.state.region.longitude,
                    latitudeDelta: this.state.region.latitudeDelta,
                    longitudeDelta: this.state.region.longitudeDelta
                }}
                region={this.state.region}
                onRegionChangeComplete={this.onRegionChangeComplete.bind(this)}>

                </MapView>
                <Image
                    style={[styles.icon, {top: this.pinY}]}
                    source={require('../images/mapPinIcon.png')}
                />
                <GooglePlacesAutocomplete
                    placeholder={I18n.t('search')}
                    minLength={2} // minimum length of text to search
                    autoFocus={false}
                    fetchDetails={true}
                    onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
                      this.onListTap(details);
                    }}
                    getDefaultValue={() => {
                      return this.props.text; // text input default value
                    }}
                    query={{
                      // available options: https://developers.google.com/places/web-service/autocomplete
                      key: GOOGLE_GEO_APIKEY,
                      language: 'es', // language of the results
                     // types: '(cities)', // default: 'geocode'
                    }}
                    styles={{
                      description: {
                        fontWeight: 'bold',
                      },
                      predefinedPlacesDescription: {
                        color: '#1faadb',
                      },
                      container: {
                        flex:1,
                        position:'absolute',
                        top:0,
                        left:0,
                        right:0,
                      },
                      textInput: {
                        flex:1,
                        flexDirection: 'row',
                        textAlign:'left',
                        paddingLeft:10,
                        paddingRight:10,
                        marginTop:10,
                        marginLeft:10,
                        marginRight: 10,
                        height:40,
                        // borderWidth:1,
                        // borderColor:'transparent',
                        backgroundColor:'white',
                        opacity:0.9,
                      },
                      textInputContainer:{
                        backgroundColor: 'transparent',
                        borderTopWidth: 0,
                        borderBottomWidth: 0
                      },
                      separator:{
                        height: 0
                      },
                      listView: {
                        backgroundColor:'white',
                        opacity:0.9,
                        marginLeft: 10,
                        marginRight: 10,
                      }
                    }}
                    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',
                    }}
                    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
                    enablePoweredByContainer={false}
                  />
              </View>
            );
        }else{
            return(<Text>{I18n.t('loading')}</Text>);
        }
    }
}

Error message: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of StaticRenderer.

@janroures Can you capture the output after running npm ls --depth=0 inside your project and paste here as a gist?

Hm. I just saw in the output that the version of the library is 1.2.2. let me try and downgrade it and I'll come back to you. Thanks.

@janroures GOTCHA!

@myaskevich
Thanks for the detail explanation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mbelgrader picture mbelgrader  路  4Comments

frankfaustino picture frankfaustino  路  4Comments

akhlopyk picture akhlopyk  路  3Comments

RajanPN picture RajanPN  路  3Comments

sohel-tech picture sohel-tech  路  3Comments