Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@placekit/autocomplete-react

Package Overview
Dependencies
Maintainers
2
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@placekit/autocomplete-react

PlaceKit Autocomplete React library

  • 1.4.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
342
increased by106.02%
Maintainers
2
Weekly downloads
 
Created
Source

PlaceKit Autocomplete React Library

All-in-one autocomplete experience for your React web apps

NPM LICENSE

Quick startComponent propertiesCustom hookAvoid re-rendersLicense


PlaceKit Autocomplete React Library is a React wrapper of PlaceKit Autocomplete JS. It features a compoment ready to use, and a custom hook for custom implementations. It also is TypeScript compatible.

🎯 Quick start

First, install PlaceKit Autocomplete React using npm package manager:

npm install --save @placekit/autocomplete-react

Then import the package and perform your first address search:

import { PlaceKit } from '@placekit/autocomplete-react';

const MyComponent = (props) => {
  return (
    <PlaceKit
      apiKey="<your-api-key>"
      options={{
        countries: ['fr']
      }}
    />
  );
};

export default MyComponent;

Important: the countries option is required at search time, but we like to keep it optional across all methods so developers remain free on when and how to define it.

Also, import default style from @placekit/autocomplete-js/dist/placekit-autocomplete.css (@placekit/autocomplete-js is set as a dependency of this package and will automatically be installed). It will style the suggestions list and the input. If you have trouble importing CSS from node_modules, copy/paste its content into your own CSS.

👉 Check out our examples for different use cases!

⚙️ Component properties

<PlaceKit
  // component options
  useGeolocation={false} // hide "ask geolocation" button
  className="your-custom-classes" // <div> wrapper custom classes

  // PlaceKit Autocomplete JS options
  apiKey="<your-api-key>"
  options={{
    offset: 4,
    template: (item, index) => {},
    formatValue: (item) => {},
    noResults: '',
    strategy: 'absolute',
    flip: false,
    countryAutoFill: false,
    className: 'panel-custom-class',
    timeout: 5000,
    maxResults: 5,
    types: ['city'],
    language: 'fr',
    countryByIP: false,
    countries: ['fr'],
    coordinates: '48.86,2.29',
  }}

  // event handlers (⚠️ use useCallback, see notes)
  onOpen={() => {}}
  onClose={() => {}}
  onResults={(query, results) => {}}
  onPick={(value, item, index) => {}}
  onError={(error) => {}}
  onDirty={(bool) => {}}
  onEmpty={(bool) => {}}
  onFreeForm={(bool) => {}}
  onGeolocation={(bool, position) => {}}
  onState={(state) => {}}

  // other HTML input props get forwarded
  id="my-input"
  name="address"
  placeholder="Search places..."
  disabled={true}
  defaultValue="France"
  // ...
/>

Please refer to PlaceKit Autocomplete JS documentation for more details about the options.

Some additional notes:

  • The <input> is using React ref attribute. It is therefore an uncontrolled component and should be treated as such.
  • If you want to customize the input style, create your own component using our custom hook. You can reuse our component as a base.
  • If you want to customize the suggestions list style, don't import our stylesheet and create your own following PlaceKit Autocomplete JS documentation.
  • Handlers are exposed directly as properties for ease of access.
  • It's recommended to memoize handler functions with useCallback, see Avoid re-renders.
  • ⚠️ Passing a non-empty value to defaultValue will automatically trigger a first search request when the user focuses the input.

🪝 Custom hook

If our component doesn't suit your needs, you can build your own using the provided custom hook usePlaceKit():

import { usePlaceKit } from '@placekit/autocomplete-react';

const MyComponent = (props) => {
  const { target, client, state } = usePlaceKit('<your-api-key>', {
    countries: ['fr'],
  });

  return (
    <input ref={target} />
  );
};

Please refer to PlaceKit Autocomplete JS documentation for more details about the options.

Some additional notes:

  • target is a React ref object.
  • The handlers can be passed through options.handlers, but also be set with client.on() (better use a useState() in that case).
  • state exposes stateless client properties (dirty, empty, freeForm, geolocation) as stateful ones.

⚠️ NOTE: you are not allowed to hide the PlaceKit logo unless we've delivered a special authorization. To request one, please contact us using our contact form.

🔁 Avoid re-renders

Because of the way React works, object/array/function literals are always considered fresh values and may cause unnecessary re-renders.

<PlaceKit> is mostly just a wrapper around PlaceKit Autocomplete JS: it uses useEffect to mount it and update options. We've made it quite resilient to updates, but each time options updates, pka.configure() is called and makes some computations.

To avoid unnecessary re-renders, memoize or hoist those literals:

import { PlaceKit } from '@placekit/autocomplete-react';
import { useCallback } from 'react';

// hoisting option functions (declaring outside of the component)
const formatValue = (item) => item.name;

const MyComponent = (props) => {

  // memoizing event handlers with useCallback
  const handlePick = useCallback(
    (value, item) => {
      console.log(item);
    },
    []
  );

  return (
    <PlaceKit
      apiKey="<your-api-key>"
      options={{
        countries: ['fr'],
        formatValue,
      }}
      onPick={handlePick}
    />
  );
};

⚠️ If you need apiKey to be set dynamically, use useMemo to memoize it, otherwise the whole autocomplete will reset at each component update, flushing the suggestions list.

⚖️ License

PlaceKit Autocomplete React Library is an open-sourced software licensed under the MIT license.

FAQs

Package last updated on 08 Jun 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc