DEV Community

Cover image for React Native - Create an autocomplete search bar with Google Places autocomplete
Jaspreet kaur
Jaspreet kaur

Posted on

React Native - Create an autocomplete search bar with Google Places autocomplete

For my last project, I created a React Native app for checking weather conditions powered by Open weather API. Open weather has different APIs to show current weather, hourly weather, weather forecast for 5 days and so on. The API can be called using latitude, longitude for any place Eg-
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
To make things easier, they also have built-in API requests by city name and other options as well Eg-
https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}

Now to make this API work, all we need to do is get the city name from the search bar.

Search bar
A simple Search bar can be created using TextInput component in React Native and setting the state for place. By default, this search bar will not autocomplete the search input. I wanted to create a search bar with an autocomplete feature to add more convenience for the user. Now, there were some other options apart from google autocomplete component, but Google autocomplete library for react native was quite easier to understand and implement.

Image description

The Google Autocomplete search bar can be created by following the below steps-
1. Download the react native google places autocomplete library-

Run `npm i react-native-google-places-autocomplete` 
Enter fullscreen mode Exit fullscreen mode

link

2.Create the Google Places API key-
If you are new to creating Google API keys, no need to panic, it's quite simple, you can check out the documentation.
Go to Google Cloud Console and select API & Services, then go to Enabled APIs & services:

Image description
For next steps you can follow the below video, it will be easier to understand -

  • You need to enable Places API and Maps JavaScript API in Google Cloud Console

  • One thing to pay attention to is, all above steps can only be accomplished when you update your billing information. Don’t worry, you won’t be charged right away, all APIs have different pricing ranges and google also gives free credit as well which should be sufficient if you're using it for your personal projects. Google makes it compulsory for you to enable billing for your project before you can use the Places API or any other API. you can check the pricing and billing info here and here too

For easy understanding of how billing works you can go on Google Maps Platform

Here you will see that a $200 credit is given to you for free every month, but if you exceed this limit then you will be charged. So you need to keep a track of your API calls per day or you can add a limit to your per day calls. Based on $200 credit you can check how many calls are free, by checking on the calculator slider provided on the same page. There are different APIs with different price ranges, choose the API you are working with to check allowed calls by setting the price range to $200, It's easy to check. For a deeper understanding please go to the FAQ section on this page.

It's always better to get assured of any kind of billing information by going through their documentation. I strongly recommend this.

3.Hiding the API key -
Once you have created the key you need to hide it, to avoid any kind of misuse of the API key created by you. Afterall, your calls are limited right? and nobody likes sudden surprises since you have linked your billing info while creating this key.

One way is by adding Google recommended restrictions to your API key-

Google strongly recommends that you restrict your API keys by limiting their usage to only those APIs needed for your application. Restricting API keys adds security to your application by protecting it from unwarranted requests.

The second way of hiding the key, is not to use the key directly in your code but hide it in the .env file-If you put the key directly in your code and push it to github it will be visible to all and it can be misused. (This is only applicable to personal projects that won’t be released on app stores).

  • Download npm i babel-plugin-inline-dotenv in your react native project. Check the npm library here

Replace your babel.cofig.js file with below code:

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      ["inline-dotenv",{
        path: '.env' 
      }]
    ],
  };
};
Enter fullscreen mode Exit fullscreen mode

Now create a .env file in the root directory and add your API keys there for eg:
API_KEY= your copied api key

You can use it in your code as:
key = process.env.API_KEY

4.Create a search bar with google autocomplete-
Use the useState hook to set the state for place.To understand the structure of the data received as a result of our place selection, just console.log the data.
Then set the place to the city name received from data.

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

const GooglePlacesInput = () => {
const [place, setPlace] = React.useState(' ')

return (
    <GooglePlacesAutocomplete
      placeholder='Search'
      onPress={(data, details = null) => {
       fetchDetails={true}
        console.log(data, details);
        setPlace(data.structured_formatting.main_text)
      }}
      query={{
        key: process.env.API_KEY,
        language: 'en',
      }}
    />
  );
};

Enter fullscreen mode Exit fullscreen mode

5.Style your search bar with some CSS:
You can checkout the Styling section in here
GooglePlacesAutocomplete can be easily customized to meet the required styles of your app. Pass styles props to GooglePlacesAutocomplete with style objects for different elements.

<GooglePlacesAutocomplete
    placeholder='Enter Location'
    minLength={2}
   autoFocus={false}
    returnKeyType={'default'}
    fetchDetails={true}
    styles={{
    textInputContainer: {
      backgroundColor: 'grey',
    },
    textInput: {
      height: 38,
      color: '#5d5d5d',
      fontSize: 16,
    },
    predefinedPlacesDescription: {
      color: '#1faadb',
    },
  }}
placeholder='Search'
      onPress={(data, details = null) => {
       fetchDetails={true}
        console.log(data, details);
        setPlace(data.structured_formatting.main_text)
      }}
      query={{
        key: process.env.API_KEY,
        language: 'en',
      }}  />

Enter fullscreen mode Exit fullscreen mode

Conclusion
In this article, we learnt how to create a Google Autocomplete search bar, create a Google place API key, how to hide the key, and use the GooglePlacesAutocomplete component into the code along with some CSS. Hope this will help you create your own search bar with autocomplete feature.

Top comments (0)