Giter VIP home page Giter VIP logo

react-loqate's Introduction

React-Loqate

This is a React implementation of the loqate APIs. It features an input, typing in which will result in a list of address options. Clicking an option will trigger your callback with that option.

Usage

Notes

You must polyfill fetch.

Installation

npm install react-loqate

Example

import AddressSearch from 'react-loqate';
// to use the default styles for the default components
import 'react-loqate/dist/index.css';

// ...
<AddressSearch
  locale="en-GB"
  apiKey="AA11-AA11-AA11-AA11"
  onSelect={(address) => console.log(address)}
/>;
// ...

Props

name type required example description
apiKey string yes "AA11-AA11-AA11-AA11" Loqate API key
locale string yes "en-GB" Language to be used
onSelect (address) => void yes address => console.log(address) Callback with for Loqate response
countries string[] no ["GB", "NL"] Countries to search in
limit number no 10 Number of options to show
classes { input?: string, list?: string, listItem?: string} no { list: 'list' } Classnames for the components
components see Customization no { Input: CustomInput, List: CustomList, ListItem: CustomListItem, } Components to overwrite the default ones
inline boolean no true Render results inline with the input
debounce number no 100 Debounce the calls to the Loqate API

Customization

You can either style the default input, list and listitem with their respective classes or replace them completely by passing in your own components in the components prop.

Custom Input and List components must forward a ref!

All custom components must pass down their props!

import React from 'react';
import AddressSearch from 'react-loqate';

<AddressSearch
  // ...
  components={{
    List: forwardRef(({ className, ...rest }, ref) => (
      <ul
        className={clsx('react-loqate-default-list', className)}
        ref={ref}
        // ...
        {...rest}
      />
    )),
    ListItem: ({ suggestion, ...rest }) => (
      <li
        onKeyDown={(e) => {
          if (e.key === 'ArrowDown') {
            e.preventDefault();
            const next = e.target.nextSibling;
            if (next) {
              next.focus();
            }
          }
          if (e.key === 'ArrowUp') {
            e.preventDefault();
            const previous = e.taget.previousSibling;
            if (previous) {
              previous.focus();
            }
          }
        }}
        {...rest}
      >
        `${suggestion.Text} ${suggestion.Description}`
      </li>
    ),
  }}
  classes={{ Input: classes.input }}
/>;

Errors

Two types of errors can be thrown, LoqateError and ReactLoqateError. Loqate Errors are errors from the Loqate API. Their structure, causes and resolutions can be found in the loqate docs.

Currently only one ReactLoqateError can be thrown. This error occurs when the Retrieve API returns an empty Items array after querying it with an existing ID.

It is on you as the implementing party to catch and handle these errors.

Contributing

This codebases use @changesets for release and version management

  • Create a feature branch with new features / fixes
  • When your code changes are complete, add a changeset file to your feature branch using pnpm changeset
  • Create a PR to request your changes to be merged to main
  • After your PR is merged, GitHub actions will create a release PR or add your changeset to an existing release PR
  • When the release is ready merge the release branch. A new version will automatically be released.

react-loqate's People

Contributors

bramkaashoek avatar contexd avatar github-actions[bot] avatar jackall3n avatar korsvanloon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-loqate's Issues

Simple example needed

Hi folks,

Please help.

I'd really like to use this in our first react app but I can't figure out how to do it. Would it be possible to add a simple example to the home page that shows what needs to be imported and how the search box would be emitted?

Sorry for bothering you. I used 'AddressSearch' as the name of the component just as your example showed. Please ignore me. But thanks for providing this!

How to change the loqate api URL ?

I am trying to use react-locate and figured that the API endpoint used is preconfigured. I have a situation where I need to use a proxy to fetch the value as the loqate endpoint will be behind the proxy. How can I do that ?

React warning: children with the same key

Because Loqate address ids are not unique, the list items in the suggestions will have duplicate keys.

How to reproduce:

For a Dutch address, search for "bal" and select Balkbrug

Suggested solution:

Add the index to the key e.g. key={sug.Id+index}

Does this work in React 18

Hi. I'm using the component as per the docs, but in a React 18 app. I'm seeing the network request come back with results, but no suggestions are displayed. The <ul> in the DOM for the address suggestions has no child <li> elements, and it is hidden - both of which imply the component is not correctly setting the suggestions even though the network request is successful and contains suggested addresses.

Presumably this component does work in React 17, so I'm wondering whether there's something about the implementation that makes it not work in React 18. Any chance it's been tested in React 18?

Reset input value

I tried hooking this up to react hook form but unable to reset the field input value, how do I reset the field?

Unable to cleanly handle a misconfigured Loqate account

You may decide this falls outside your remit, and that's fine.

If a user has entered an invalid API key, or is out of credit, or needs to agree to some updated policies, a packet will be returned in the following format (example - incorrect key):

{"Items":
  [
    { "Error":"2",
      "Description":"Unknown key",
      "Cause":"The key you are using to access the service was not found.",
      "Resolution":"Please check that the key is correct. It should be in the form AA11-AA11-AA11-AA11."
    }
  ]
}

Currently this will just get passed to the ListItem and displayed. My current workaround is to pass an additional onError prop through so I can catch it in my custom ListItem and, in my case, fall back to my standard Address input fields.

What would be really nice is to check on mount if the supplied API key will work. It looks like simply performing a call with no Text= is enough to elicit an error response, which responds with Error code 1001 (Text or Container Required) in the case of a successful call, and any other value meaning there is an issue, but I haven't tested all the permutations.

Countries in api request is not updated

If you change the country prop, the subsequent api calls don't take the new country into account.
I think you need to wrap the find function in a useCallback with the countries prop as a dependency.

Two Accessibility Issues

the list of suggestions is not accessible with arrows, most screen readers and other assistive technologies will not understand the element.
Also, the aria-label of all the list items will have the same value (which is the search keyword) rather than the suggestions themselves (the list item's content). This will lead, for example, to repeatedly hear the postcode numerous times, not the actual addresses to select from. See below:
loqate1

There is no way to customize the input to return the suggestions as a datalist, that would be the ideal solution for all scenarios.

Thank you for the great package and for the good work BTW.

Error handling

Hi team,

I'm looking for some guidance on how to catch loqate errors thrown from react-loqate?

Specifically need to handle this error:
{"Error":"3","Description":"Account out of credit","Cause":"Your account is either out of credit or has insufficient credit to service this request.","Resolution":"Please check your account balance and top it up if necessary."}

I'm using a custom Input and custom List component. I want to catch the error and prompt the user to enter address manually. Any help would be much appreciated!

material-ui dependency issue

Do we still use @material-ui/core as a dependency? I'm seeing they changed their library to @mui/material now.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.