Jude Williams

Jude Williams

1582171500

React hook for Google Maps Places Autocomplete

usePlacesAutocomplete

This is a React hook of Google Maps Places Autocomplete, which helps you build an UI component with the feature of place autocomplete easily! By leverage the power of Google Maps Places API, you can provide a great UX (user experience) for user interacts with your search bar or form etc. Hope you guys it.

usePlacesAutocomplete

Features

Requirement

To use use-places-autocomplete, you must use [[email protected]](/cdn-cgi/l/email-protection) or greater which includes hooks.

Installation

This package is distributed via npm.

$ yarn add use-places-autocomplete
# or
$ npm install --save use-places-autocomplete

Getting Started

usePlacesAutocomplete is based on the Places Autocomplete (or more specific docs) of Google Maps Place API. If you are unfamiliar with these APIs, we recommend you reviewing them before we start.

Setup APIs

To use this hook, there’re two things we need to do:

  1. Enable Google Maps Places API.
  2. Get an API key.

Load the library

Use the script tag to load the library in your project.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

We also support asynchronous script loading. By doing so you need to pass the initMap as the callbackName option.

<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
></script>

⚠️ If you got a global function not found error. Make sure usePlaceAutocomplete is declared before the script is loaded.

Create the component

Now we can start to build our component. Check the API out to learn more.

import usePlacesAutocomplete, { getGeocode, getLatLng } from 'use-places-autocomplete';
import useOnclickOutside from 'react-cool-onclickoutside';

const PlacesAutocomplete = () => {
  const {
    ready,
    value,
    suggestions: { status, data },
    setValue,
    clearSuggestions
  } = usePlacesAutocomplete({
    requestOptions: { /* Define search scope here */ }
    debounce: 300
  });
  const registerRef = useOnclickOutside(() => {
    // When user clicks outside of the component, we can dismiss
    // the searched suggestions by calling this method
    clearSuggestions();
  });

  const handleInput = e => {
    // Update the keyword of the input element
    setValue(e.target.value);
  };

  const handleSelect = ({ description }) => () => {
    // When user selects a place, we can replace the keyword without request data from API
    // by setting the second parameter as "false"
    setValue(description, false);
    clearSuggestions();

    // Get latitude and longitude via utility functions
    getGeocode({ address: description })
      .then(results => getLatLng(results[0]))
      .then(({ lat, lng }) => {
        console.log('📍 Coordinates: ', { lat, lng });
      }).catch(error => {
        console.log('😱 Error: ', error)
      });
  };

  const renderSuggestions = () =>
    data.map(suggestion => {
      const {
        id,
        structured_formatting: { main_text, secondary_text }
      } = suggestion;

      return (
        <li
          key={id}
          onClick={handleSelect(suggestion)}
        >
          <strong>{main_text}</strong> <small>{secondary_text}</small>
        </li>
      );
    });

  return (
    <div ref={registerRef}>
      <input
        value={value}
        onChange={handleInput}
        disabled={!ready}
        placeholder="Where are you going?"
      />
      {/* We can use the "status" to decide whether we should display the dropdown or not */}
      {status === 'OK' && <ul>{renderSuggestions()}</ul>}
    </div>
  );
};

Easy right? This is the magic of the usePlacesAutocomplete ✨. I just show you how does it work via the minimal example. However there’re more things you can do for an UX rich autocomplete component, like WAI-ARIA compliant and keyword support as my demo (check the code), a keyword clear button, search history etc.

💡 react-cool-onclickoutside is my other hook library, which can help you handle the interaction of user clicks outside of the component(s).

API

const return = usePlacesAutocomplete(parameter);

Parameter object (optional)

When use usePlacesAutocomplete you can configure the following options via the parameter.

Key Type (all optional) Default Description
requestOptions object The request options of Google Maps Places API except for input (e.g. bounds, radius etc.).
googleMaps object window.google.maps In case you want to provide your own Google Maps object, pass it in as google.maps.
callbackName string You can provide a callback name to initialize usePlacesAutocomplete after Google script is loaded. It’s useful when you load the script asynchronously.
debounce number 200 Number of milliseconds to delay before making a request to Google Maps Places API.

Return object

It’s returned with the following properties.

Key Type Default Description
ready boolean false The ready status of usePlacesAutocomplete.
value string '' value for the input element.
suggestions object { loading: false, status: '', data: [] } See suggestions.
setValue function (value, shouldFetchData = true) => {} See setValue.
clearSuggestions function See clearSuggestions.

suggestions

The search result of Google Maps Places API, which contains the following properties:

  • loading: boolean - indicates the status of a request is pending or has completed. It’s useful for displaying a loading indicator for user.
  • status: string - indicates the status of API response, which has these values. It’s useful to decide whether we should display the dropdown or not.
  • data: array - an array of suggestion objects each contains all the data.

setValue

Set the value of the input element. Use case as below.

import usePlacesAutocomplete from 'use-places-autocomplete';

const PlacesAutocomplete = () => {
  const { value, setValue } = usePlacesAutocomplete();

  const handleInput = e => {
    // Place a "string" to update the value of the input element
    setValue(e.target.value);
  };

  return (
    <div>
      <input value={value} onChange={handleInput} />
      {/* Render dropdown */}
    </div>
  );
};

In addition, the setValue method has an extra parameter, which can be used to disable hitting Google Maps Places API.

import usePlacesAutocomplete from 'use-places-autocomplete';

const PlacesAutocomplete = () => {
  const {
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete();

  const handleSelect = ({ description }) => () => {
    // When user select a place, we can replace the keyword without request data from API
    // by setting the second parameter to "false"
    setValue(description, false);
  };

  const renderSuggestions = () =>
    data.map(suggestion => (
        <li
          key={suggestion.id}
          onClick={handleSelect(suggestion)}
        >
          {/* Render suggestion text */}
        </li>
      )
    });

  return (
    <div>
      <input value={value} onChange={handleInput} />
      {status === 'OK' && <ul>{renderSuggestions()}</ul>}
    </div>
  );
};

clearSuggestions

Calling the method will clear and reset all the properties of the suggestions object to default. It’s useful for dismissing the dropdown.

import usePlacesAutocomplete from 'use-places-autocomplete';
import useOnclickOutside from 'react-cool-onclickoutside';

const PlacesAutocomplete = () => {
  const {
    value,
    suggestions: { status, data },
    setValue,
    clearSuggestions
  } = usePlacesAutocomplete();
  const registerRef = useOnclickOutside(() => {
    // When user clicks outside of the component, call it to clear and reset the suggestions data
    clearSuggestions();
  });

  const renderSuggestions = () =>
    data.map(suggestion => (
        <li
          key={suggestion.id}
          onClick={handleSelect(suggestion)}
        >
          {/* Render suggestion text */}
        </li>
      )
    });

  return (
    <div ref={registerRef}>
      <input value={value} onChange={handleInput} />
      {/* After calling the clearSuggestions(), the "status" is reset so the dropdown is hidden */}
      {status === 'OK' && <ul>{renderSuggestions()}</ul>}
    </div>
  );
};

Utility Functions

We provide getGeocode and getLatLng utils for you to do geocoding and get geographic coordinates when needed.

getGeocode

It helps you convert address (e.g. “Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan”) into geographic coordinates (e.g. latitude 25.033976 and longitude 121.5645389) by Google Maps Geocoding API.

import { getGeocode } from 'use-places-autocomplete';

const parameter = {
  address: 'Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan',
  // or
  placeId: 'ChIJraeA2rarQjQRPBBjyR3RxKw'
};

getGeocode(parameter)
  .then(results => {
    console.log('Geocoding results: ', results);
  })
  .catch(error => {
    console.log('Error: ', error);
  });

getGeocode is an asynchronous function with the following API:

  • parameter: object - you must supply one, only one of address or placeId. It’ll be passed as Geocoding Requests.
  • results: array - an array of objects each contains all the data.
  • error: string - the error status of API response, which has these values (except for “OK”).

getLatLng

It helps you get the lat and lng from the result object of getGeocode.

import { getGeocode, getLatLng } from 'use-places-autocomplete';

const parameter = {
  address: 'Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan'
};

getGeocode(parameter)
  .then(results => getLatLng(results[0]))
  .then(latLng => {
    const { lat, lng } = latLng;

    console.log('Coordinates: ', { lat, lng });
  });

getLatLng is an asynchronous function with the following API:

  • parameter: object - the result object of getGeocode.
  • latLng: object - contains the latitude and longitude properties.

GitHub

Author: wellyshen

Live Demo: https://use-places-autocomplete.netlify.com/

GitHub: https://github.com/wellyshen/use-places-autocomplete

#reactjs #javascript

What is GEEK

Buddha Community

React hook for Google Maps Places Autocomplete

I am Developer

1614263355

Google Places Autocomplete In PHP with Example

PHP 8 google address autocompletes without showing the map. In this tutorial, i will show youhow to create a google autocomplete address web app using google address APIs in PHP.

Note that, Google autocomplete address API will return address and as well as latitude, longitude, place code, state, city, country, etc. Using latitude and longitude of address, you can show markers location in google map dynamically in php.

This tutorial guide to you step by step how to implement google places autocomplete address web application without showing google maps in PHP.

For implementing the autocomplete address in php, you will have to get the key from google console app. So, just go to the link https://cloud.google.com and get the google API key.

https://www.tutsmake.com/php-google-places-autocomplete-example/

#autocomplete address google api php #google places autocomplete example in php #google places autocomplete example without map in php #php google places autocomplete jquery #php google places autocomplete jquery example

Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

I am Developer

1626836644

React Google Login Example

Integrate google login in react apps; This example tutorial will show you step by step how to implement google login in react apps using javascript SDK.

If you want to integrate google login authentication in your react app. So you will not need any react plugin for this. In this tutorial, you will learn how to add a google login button in react app without any react plugin.

Before you can integrate Google Sign-In into your react app, you must create a client ID, which you need to call the sign-in API.

To create a Google API Console project and client ID, go to the APIs & Services dashboard and then follow the following steps:

Step 1: Visit Google Developer Console. And create a new project as following in below picture:

Step 2: you will see the screen looks like, show here you can set your project name as you want.

Step 3: Now you have successfully created a new project. After that, you need to select the created projects on the top menu. Then click on OAuth consent screen and select the given option according to your requirement:

Step 4: when you will be done above. After that automatically appear below given screen. In this screen, you need to fill your website URL, privacy policy URL, etc.

Step 5: you need to click on left side menu credentials and appear below screen. In this screen, you need to select OAuth client ID.

Step 6: After that, the below form will be apper. Here From different Application type options, you have to select Web application. Once you have select Web application option, then one form will appear on web page. Here you have to define Name and you have also define Authorized redirect URIs field and lastly click on Create button.

Step 7: the pop looks like below in picture automatically appear. Once you have click on the create button, then you can get your Client ID and your client secret key. You have to copy both key for future use for implement Login using Google account using PHP.

Please note that, google client id and secret.

How to Add Google Login to your React Apps

  • Step 1 - Create React App
  • Step 2 - Install Bootstrap 4 Library
  • Step 3 - Create Google Login Component
  • Step 4 - Import Google Login Component in App.js

https://www.tutsmake.com/react-google-login-button-example/

#react-google-login component #react-google-login demo #google login with react #add google login button to react

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook