paint-brush
Create your React.js Address Autocomplete Component in 10 minutes ⏰ by@welly
12,365 reads
12,365 reads

Create your React.js Address Autocomplete Component in 10 minutes ⏰

by wellyFebruary 12th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Hi guys, I want to introduce use-places-autocomplete. It's a React.js hook for Google Maps Places Autocomplete. With it you can build your own places autocomplete UI like the following demo easily! Hope you guys 👍🏻 it.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Create your React.js Address Autocomplete Component in 10 minutes ⏰
welly HackerNoon profile picture
Hi guys, I want to introduce . It's a React.js  for . With it you can build your own places autocomplete UI like the following demo easily! Hope you guys 👍🏻 it.
⚡️ Try yourself: 

Features

  • 🧠 Provides intelligent places suggestions powered by .
  • 🎣 Builds your own customized autocomplete UI by React .
  • 🔧  to do geocoding and get geographic coordinates using .
  • 🤑 Built-in  for you to save the cost of Google APIs.
  • 💰 Built-in debounce mechanism for you to lower the cost of Google APIs.
  • 🚀 Supports asynchronous Google script loading.
  • 📜 Supports  type definition.
  • ⌨️ Builds a UX-rich component (e.g.  and keyword support) via comprehensive .
  • 🦔 Tiny size (). No external dependencies, aside for the react.

How does it work?

First, use the script tag to load the library in your project.
<script src="//maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
Start to build our component. Check the  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 ref = 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 to "false"
      setValue(description, false);
      clearSuggestions();

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

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

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

  return (
    <div ref={ref}>
      <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  and keyword support as my  (check the ), a keyword clear button, search history etc.

💡  is my other hook library, which can help you handle the interaction of user clicks outside of the component(s).
Thanks for reading, for more usage details checkout the project's GitHub page: You can also install this package is distributed via .
$ yarn add use-places-autocomplete
# or
$ npm install --save use-places-autocomplete

When working with TypeScript you need to install the  as a devDependencies.

$ yarn add --dev @types/googlemaps
# or
$ npm install --save-dev @types/googlemaps


바카라사이트 바카라사이트 온라인바카라