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-autosuggest-vantage

v1.0.3

Published

WAI-ARIA compliant React autosuggest component

Downloads

26

Readme

React Autosuggest

WAI-ARIA compliant React autosuggest component.

Live Examples

  • Basic example
  • Custom renderer
  • Multiple sections
  • Controlled Component
  • Events playground

Features

Installation

npm install react-autosuggest --save

or

bower install react-autosuggest --save

Basic Usage

CommonJS module:

import Autosuggest from 'react-autosuggest';

const suburbs = ['Cheltenham', 'Mill Park', 'Mordialloc', 'Nunawading'];

function getSuggestions(input, callback) {
  const regex = new RegExp('^' + input, 'i');
  const suggestions = suburbs.filter(suburb => regex.test(suburb));

  setTimeout(() => callback(null, suggestions), 300); // Emulate API call
}
<Autosuggest suggestions={getSuggestions} />

UMD module:

Check out the standalone example.

Options

suggestions (required)

Implement this function to tell Autosuggest which suggestions to display.

function(input, callback) {
  ...
}
  • input - Will be the value of the input field

  • callback - Should be called once the suggestions are in hand, or error occurs.

    • Success example: callback(null, <suggestions>)
    • Error example: callback(new Error("Couldn't get locations"))

<suggestions> can have one of the following two formats:

  • To display a single section with no title: [<suggestion>, <suggestion>, ...]
  • To display one or more sections with optional titles: Array of objects with an optional sectionName and a mandatory suggestions keys, e.g.:
[{
  suggestions: [<suggestion>, <suggestion>]   // This section won't have a title
}, {
  sectionName: 'Second section',
  suggestions: [<suggestion>, <suggestion>, <suggestion>]
}]

<suggestion> can have one of the following two formats:

  • String, e.g.: 'Mentone'
  • Object, e.g.: { suburb: 'Mentone', postcode: '3194' }. This object cannot have a suggestions key. You must implement suggestionRenderer and suggestionValue in this case.

suggestionRenderer (required when suggestions are objects)

This function will be used to render the suggestion. It should return ReactElement or a string.

function(suggestion, input) {
  ...
}
  • suggestion - The suggestion to render
  • input - The value of the input field (e.g.: 'Men'). If user interacts using the Up or Down keys at the moment, it will be the value of the input field prior to those interactions.

For example:

function renderSuggestion(suggestion, input) { // In this example, 'suggestion' is a string
  return (                                     // and it returns a ReactElement
    <span><strong>{suggestion.slice(0, input.length)}</strong>{suggestion.slice(input.length)}</span>
  );
}
<Autosuggest suggestions={getSuggestions}
             suggestionRenderer={renderSuggestion} />

suggestionValue (required when suggestions are objects)

This function will be used to set the value of the input field when suggestion is selected. It has one parameter which is the suggestion object. This function is ignored when suggestions are strings.

For example:

function getSuggestionValue(suggestionObj) {
  return suggestionObj.suburb + ' VIC ' + suggestionObj.postcode;
}
<Autosuggest suggestions={getSuggestions}
             suggestionRenderer={renderSuggestion}
             suggestionValue={getSuggestionValue} />

defaultValue (optional)

You may use defaultValue only if you want Autosuggest to behave in an uncontrolled manner (the component keeps track of its state internally). In this case you cannot use value.

defaultValue is simply the initial value of the input.

For example:

<Autosuggest suggestions={getSuggestions}
             defaultValue="Mordialloc"
             ... />

value (optional)

When specified, Autosuggest behaves in a controlled manner (the component uses an outside source of state).

value is simply the value of the input.

For example:

<Autosuggest suggestions={getSuggestions}
             value={this.state.autosuggestValue}
             ... />

When value is not specified, Autosuggest behaves in an uncontrolled manner (the component keeps track of its state internally).

showWhen (optional)

This function will be used to determine whether to show suggestions or not. It has one parameter which is the value of the input field (e.g.: 'm '). The default is:

function(input) {
  return input.trim().length > 0;
}

For example, this is how you could show suggestions only when user typed 2 or more characters:

<Autosuggest suggestions={getSuggestions}
             showWhen={input => input.trim().length >= 2} />

onSuggestionSelected (optional)

This function will be called when suggestion is selected via mouse click or Enter.

function(suggestion, event) {
  ...
}
  • suggestion - The selected suggestion
  • event - It can be used to call event.preventDefault() if the Autosuggest is inside a form and you don't want to submit the form once user selected a suggestion using Enter.

For example:

function onSuggestionSelected(suggestion, event) {
  event.preventDefault();
  // Do other fancy stuff
}
<Autosuggest suggestions={getSuggestions}
             onSuggestionSelected={onSuggestionSelected} />

onSuggestionFocused (optional)

This function will be called when suggestion is focused via mouse hover or Up/Down keys.

function(suggestion) {
  ...
}

For example:

function onSuggestionFocused(suggestion) { // In this example 'suggestion' is a string
  console.log('Suggestion focused: [' + suggestion + ']');
}
<Autosuggest suggestions={getSuggestions}
             onSuggestionFocused={onSuggestionFocused} />

onSuggestionUnfocused (optional)

This function will be called when suggestion is unfocused.

function(suggestion) {
  ...
}

For example:

function onSuggestionUnfocused(suggestion) { // In this example 'suggestion' is a string
  console.log('Suggestion unfocused: [' + suggestion + ']');
}
<Autosuggest suggestions={getSuggestions}
             onSuggestionUnfocused={onSuggestionUnfocused} />

inputAttributes (optional)

Hash of attributes to pass to the input field. For example:

const inputAttributes = {
  id: 'locations-autosuggest',
  name: 'locations-autosuggest',
  className: 'my-sweet-locations-autosuggest',
  placeholder: 'Enter locations...',
  type: 'search',
  onChange: value => console.log(`Input value changed to: ${value}`),
  onBlur: event => console.log('Input blurred. Event:', event)
};
<label htmlFor="locations-autosuggest">Where</label>
<Autosuggest suggestions={getSuggestions}
             inputAttributes={inputAttributes} />

cache (optional)

Defaults to true, meaning that the suggestions function will be called only once for a given input.

For example, if user types m, and suggestions are retrieved, we store the result in memory. Then, if user types e and hits Backspace, we get the suggestions for m from the cache.

Set cache={false} to disable this behaviour.

id (required when multiple Autosuggests are rendered on a page)

The only reason id exists, is to set ARIA attributes (they require a unique id).

When rendering a single Autosuggest, don't set the id (it will be set to '1', by default).

When rendering multiple Autosuggests, make sure to give them unique ids. For example:

<Autosuggest id="source" suggestions={getSourceSuggestions} />
<Autosuggest id="destination" suggestions={getDestinationSuggestions} />

scrollBar (optional)

Set it to true only if suggestions container (react-autosuggest__suggestions) can have a scroll bar (e.g. if it has height: 200px; overflow: auto). Suggestions container must be a positioned element in this case. When set to true, suggestions container will adjust its scroll bar every time user interacts using the Up and Down keys (see the [this example](https://moroshko.github.io/react-autosuggest#Custom renderer)).

Defaults to false.

theme (optional)

Autosuggest comes with no styles, and it supports react-themeable.

This means you can use CSS Modules, Radium, React Style, JSS, inline styles, or even global CSS to style your Autosugest component.

For example, to style the Autosuggest using CSS Modules, do:

/* theme.css */

.root { ... }
.suggestions { ... }
.suggestion { ... }
.suggestionIsFocused { ... }
.section { ... }
.sectionName { ... }
.sectionSuggestions { ... }
import theme from 'theme.css';
<Autosuggest theme={theme} ... />

When not specified, theme defaults to:

{
  root: 'react-autosuggest',
  suggestions: 'react-autosuggest__suggestions',
  suggestion: 'react-autosuggest__suggestion',
  suggestionIsFocused: 'react-autosuggest__suggestion--focused',
  section: 'react-autosuggest__suggestions-section',
  sectionName: 'react-autosuggest__suggestions-section-name',
  sectionSuggestions: 'react-autosuggest__suggestions-section-suggestions'
}

An example of styling the Autosuggest using these global classes can be found in examples/src/Autosuggest.less

The following diagrams explain the classes above.

No sections
+---| react-autosuggest |-------------------------+
|                                                 |
|  <input>                                        |
|                                                 |
|  +--| react-autosuggest__suggestions |-------+  |
|  |                                           |  |
|  |  +--| react-autosuggest__suggestion |--+  |  |
|  |  |                                     |  |  |
|  |  +-------------------------------------+  |  |
|  |                                           |  |
|  +-------------------------------------------+  |
|                                                 |
+-------------------------------------------------+
Multiple sections
+---| react-autosuggest |----------------------------------------------------+
|                                                                            |
|  <input>                                                                   |
|                                                                            |
|  +--| react-autosuggest__suggestions |----------------------------------+  |
|  |                                                                      |  |
|  |  +--| react-autosuggest__suggestions-section |--------------------+  |  |
|  |  |                                                                |  |  |
|  |  |  +--| react-autosuggest__suggestions-section-name |---------+  |  |  |
|  |  |  |                                                          |  |  |  |
|  |  |  +----------------------------------------------------------+  |  |  |
|  |  |                                                                |  |  |
|  |  |  +--| react-autosuggest__suggestions-section-suggestions |--+  |  |  |
|  |  |  |                                                          |  |  |  |
|  |  |  |  +--| react-autosuggest__suggestion |-----------------+  |  |  |  |
|  |  |  |  |                                                    |  |  |  |  |
|  |  |  |  +----------------------------------------------------+  |  |  |  |
|  |  |  |                                                          |  |  |  |
|  |  |  +----------------------------------------------------------+  |  |  |
|  |  |                                                                |  |  |
|  |  +----------------------------------------------------------------+  |  |
|  |                                                                      |  |
|  +----------------------------------------------------------------------+  |
|                                                                            |
+----------------------------------------------------------------------------+

Development

npm start

Now, open http://localhost:3000/examples/dist/index.html and start hacking!

Running Tests

npm test

License

MIT