How to integrate google autocomplete to react application

How to integrate google autocomplete to react application

Integrating third-party scripts to react applications is tricky.

In this post, I will show you how easily you can integrate into a React application.

Let's do it. I assume you have created an application and can work on it.

We will create a hook to handle all the staff.

To load Google Map script let's install the package

npm i @googlemaps/js-api-loader

Create a hook called useGoogleMap.js and create an instance of Loader

import { Loader } from '@googlemaps/js-api-loader';

const loader = new Loader({
  apiKey: process.env.NEXT_PUBLIC_GOOGLE_KEY,
  version: 'weekly',
  libraries: ['places'],
});

Let's use the loader to load the script on component mount

import { useEffect, useState } from 'react';
import { Loader } from '@googlemaps/js-api-loader';

const loader = new Loader({
  apiKey: process.env.NEXT_PUBLIC_GOOGLE_KEY,
  version: 'weekly',
  libraries: ['places'],
});

const useGooglePlaceAutocomplete = () => {
  const [place, setPlace] = useState(null);

  const activeGoogleScript = () => {
    loader.load().then(async () => {
      const input = document.getElementById('google-place');
      if (input) {
        const options = {
          fields: [
            'formatted_address',
            'geometry',
            'name',
            'address_components',
          ],
          strictBounds: false,
        };

        const autocomplete = new google.maps.places.Autocomplete(
          input,
          options
        );

        autocomplete.addListener('place_changed', () => {
          const placeData = autocomplete.getPlace();

          if (!placeData.geometry || !placeData.geometry.location) {
            window.alert(
              "No details available for input: '" + placeData.name + "'"
            );
            return;
          }

          setPlace(placeData);
        });
      }
      setScriptLoaded(true);
    });
  };

  useEffect(() => {
    activeGoogleScript();
  }, []);


  return {
    place,
    scriptLoaded
  };
};

export default useGoogleMap;

Now script is loaded and initialized the autocomplete to google-place id input field.

So, we can use the hook to any of our React components.

import { useEffect, useState } from 'react';
import useGoogleMap from './useGoogleMap';


const AutoComplete = () => {

  const { place } = useGoogleMap();

  return (
    <div>
      <div>{place.formatted_address}</div>
      <input
          type="text"
          id="google-place"
          placeholder="Enter your city or postal code"
        />
    </div>
  );
};

export default AutoComplete;

You can get place details from the place variable.