npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-fetch-autocomplete

v0.0.5

Published

A controlled autocomplete component for react which can be used for any type of endpoint

Downloads

93

Readme

react-fetch-autocomplete

The Autocomplete control for React.

Demo on CodeSandbox: Demo page:

Installation and usage

Install it with yarn:

yarn add react-fetch-autocomplete

Or with npm:

npm install react-fetch-autocomplete

Then use it in your app:

import React from "react";
import ReactFetchAutocomplete from "react-fetch-autocomplete";

import styles from "./styles.css";

// A custom suggestion parser which should always
// return an array of objects
// containing at least a description
const suggestionParser = data =>
  data.features.map(feature => ({
    description: feature.place_name,
    coords: feature.center
  }));

const MyComponent = () => {
  const [value, setValue] = useState("");
  const [selection, setSelection] = useState(null);
  const apiKey = "Your_API_key";
  // fetchUrl is in this case a method that returns
  // a URL but can also be a plain string
  const fetchUrl = ({ searchQuery }) =>
    `http://yourendpoint.com?someParam=${searchQuery}&api_key=${apiKey}`;

  return (
    <ReactFetchAutocomplete
      value={value}
      onChange={setValue}
      onSelect={setSelection}
      fetchUrl={fetchUrl}
      suggestionParser={suggestionParser}
    >
      {({ inputProps, getSuggestionProps, suggestions, error, loading }) => {
        if (error) return <div>We have an error..</div>;
        return (
          <div>
            <input {...inputProps({ placeholder: "Search for something.." })} />
            {loading && <div>Loading..</div>}
            {suggestions.length > 0 && (
              <div>
                {suggestions.map(suggestion => (
                  <div {...getSuggestionProps(suggestion)}>
                    {suggestion.description}
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      }}
    </ReactFetchAutocomplete>
  );
};

export default MyComponent;

Props

ReactFetchAutocomplete is a Controlled Component which uses Render Props

| Prop | Type | Required | Default | Description | | --------------------------------------- | --------------- | :----------------: | :------: | ----------------------------------------------------------------------------------------------------------------------------- | | value | string | :white_check_mark: | | value input for the element | | children | function | :white_check_mark: | | Render function which handles the rendering | | suggestionParser | function | :white_check_mark: | | A function that receives the json response and returns an array of objects which should always contain a description property | | fetchUrl | function/string | :white_check_mark: | | function: Receives the latest searchQuery and returns a stringstring: a plain string | | onChange | function | | () => {} | onChange function for the input | | onSelect | function | | () => {} | When a suggestion is selected this function triggers with the current suggestion as a param | | debounce | number | | 200 | A number in miliseconds representing the delay before a request gets fired after the last key gets pressed |

value

Type: string, Required: true

children

Type: function, Required: true This method handles the rendering of your element based on the state returned by ReactFetchAutocomplete. The function returns the following params in an object:

getInputProps

This function can be spread over the <input /> element. As a parameter this function accepts an object which can be given any props the input element accepts (except for value and onChange as these are props for the ReactFetchAutocomplete).

<input {...getInputProps({placeholder: 'Your placeholder'})} />
getSuggestionItemProps

This function can be spread over each suggestion item you render. As a parameter it expects the rendered suggestion and optionally an object which can be given any props you wish to be passed to the suggestion element.

suggestions.map(suggestion => (
    <div {...getSuggestionItemProps(suggestion, { className: 'my-class'})}>{suggestion.description}</div>
))
loading

This is a boolean that returns whether or not there is a request in progress.

error

This is a boolean that returns whether or not there has been an error.

suggestions

This is an array of suggestion objecta that contain the data you passed down in the suggestionParser.

suggestionParser

Type: function, Required: true This is a function that receives the json response from the api endpoint and returns an array of objects which should contain at least a description.

const suggestionParser = data =>
  data.features.map(feature => ({
    description: feature.place_name,
    coords: feature.center,
  }));

fetchUrl

Type: function|string, Required: true function: A function that accepts the current searchString as param and returns a url to the endpoint. string: a plain string containing the url.

const fetchUrl = ({ searchQuery }) =>
  `http://yourendpoint.com?someParam=${searchQuery}`;
const fetchUrl = 'http://yourendpoint.com/';

onChange

Type: function, Required: false An event handler which can be used to update the state with the search value.

onSelect

Type: function, Required: false An event handler which can be used to update the state incase a suggestion actually gets selected.

debounce

type: 'number', Required: false A number in miliseconds representing the delay before a request gets fired after the last key gets pressed.