Giter Club home page Giter Club logo

react-autosuggest's Introduction

Build Status Contributors Coverage Status

npm Downloads npm Version gzip size

React Autosuggest

Project Status

Looking for maintainers!

Unfortunately, I don't have the time to maintain this project anymore. If you are interested to help, please reach out to me on Twitter @moroshko.

Demo

Check out the Homepage and the Codepen examples.

Features

Installation

yarn add react-autosuggest

or

npm install react-autosuggest --save

You can also use the standalone UMD build:

<script src="https://unpkg.com/react-autosuggest/dist/standalone/autosuggest.js"></script>

Basic Usage

import React from 'react';
import Autosuggest from 'react-autosuggest';

// Imagine you have a list of languages that you'd like to autosuggest.
const languages = [
  {
    name: 'C',
    year: 1972
  },
  {
    name: 'Elm',
    year: 2012
  },
  ...
];

// Teach Autosuggest how to calculate suggestions for any given input value.
const getSuggestions = value => {
  const inputValue = value.trim().toLowerCase();
  const inputLength = inputValue.length;

  return inputLength === 0 ? [] : languages.filter(lang =>
    lang.name.toLowerCase().slice(0, inputLength) === inputValue
  );
};

// When suggestion is clicked, Autosuggest needs to populate the input
// based on the clicked suggestion. Teach Autosuggest how to calculate the
// input value for every given suggestion.
const getSuggestionValue = suggestion => suggestion.name;

// Use your imagination to render suggestions.
const renderSuggestion = suggestion => (
  <div>
    {suggestion.name}
  </div>
);

class Example extends React.Component {
  constructor() {
    super();

    // Autosuggest is a controlled component.
    // This means that you need to provide an input value
    // and an onChange handler that updates this value (see below).
    // Suggestions also need to be provided to the Autosuggest,
    // and they are initially empty because the Autosuggest is closed.
    this.state = {
      value: '',
      suggestions: []
    };
  }

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue
    });
  };

  // Autosuggest will call this function every time you need to update suggestions.
  // You already implemented this logic above, so just use it.
  onSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      suggestions: getSuggestions(value)
    });
  };

  // Autosuggest will call this function every time you need to clear suggestions.
  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

  render() {
    const { value, suggestions } = this.state;

    // Autosuggest will pass through all these props to the input.
    const inputProps = {
      placeholder: 'Type a programming language',
      value,
      onChange: this.onChange
    };

    // Finally, render it!
    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        inputProps={inputProps}
      />
    );
  }
}

Props

Prop Type Required Description
suggestions Array These are the suggestions that will be displayed. Items can take an arbitrary shape.
onSuggestionsFetchRequested Function Will be called every time you need to recalculate suggestions.
onSuggestionsClearRequested Function * Will be called every time you need to set suggestions to [].
getSuggestionValue Function Implement it to teach Autosuggest what should be the input value when suggestion is clicked.
renderSuggestion Function Use your imagination to define how suggestions are rendered.
inputProps Object Pass through arbitrary props to the input. It must contain at least value and onChange.
containerProps Object Pass through arbitrary props to the container. Useful if you need to override the default props set by Autowhatever, for example, for accessibility.
onSuggestionSelected Function Will be called every time suggestion is selected via mouse or keyboard.
onSuggestionHighlighted Function Will be called every time the highlighted suggestion changes.
shouldRenderSuggestions Function When the input is focused, Autosuggest will consult this function when to render suggestions. Use it, for example, if you want to display suggestions when input value is at least 2 characters long.
alwaysRenderSuggestions Boolean Set it to true if you'd like to render suggestions even when the input is not focused.
highlightFirstSuggestion Boolean Set it to true if you'd like Autosuggest to automatically highlight the first suggestion.
focusInputOnSuggestionClick Boolean Set it to false if you don't want Autosuggest to keep the input focused when suggestions are clicked/tapped.
multiSection Boolean Set it to true if you'd like to display suggestions in multiple sections (with optional titles).
renderSectionTitle Function
when multiSection={true}
Use your imagination to define how section titles are rendered.
getSectionSuggestions Function
when multiSection={true}
Implement it to teach Autosuggest where to find the suggestions for every section.
renderInputComponent Function Use it only if you need to customize the rendering of the input.
renderSuggestionsContainer Function Use it if you want to customize things inside the suggestions container beyond rendering the suggestions themselves.
theme Object Use your imagination to style the Autosuggest.
id String Use it only if you have multiple Autosuggest components on a page.

suggestions (required)

Array of suggestions to display. The only requirement is that suggestions is an array. Items in this array can take an arbitrary shape.

For a plain list of suggestions, every item in suggestions represents a single suggestion. It's up to you what shape every suggestion takes. For example:

const suggestions = [
  {
    text: "Apple"
  },
  {
    text: "Banana"
  },
  {
    text: "Cherry"
  },
  {
    text: "Grapefruit"
  },
  {
    text: "Lemon"
  }
];

For multiple sections, every item in suggestions represents a single section. Again, it's up to you what shape every section takes. For example:

const suggestions = [
  {
    title: "A",
    suggestions: [
      {
        id: "100",
        text: "Apple"
      },
      {
        id: "101",
        text: "Apricot"
      }
    ]
  },
  {
    title: "B",
    suggestions: [
      {
        id: "102",
        text: "Banana"
      }
    ]
  },
  {
    title: "C",
    suggestions: [
      {
        id: "103",
        text: "Cherry"
      }
    ]
  }
];

onSuggestionsFetchRequested (required)

This function will be called every time you might need to update suggestions. It has the following signature:

function onSuggestionsFetchRequested({ value, reason })

where:

  • value - the current value of the input
  • reason - string describing why onSuggestionsFetchRequested was called. The possible values are:
    • 'input-changed' - user typed something
    • 'input-focused' - input was focused
    • 'escape-pressed' - user pressed Escape to clear the input (and suggestions are shown for empty input)
    • 'suggestions-revealed' - user pressed Up or Down to reveal suggestions
    • 'suggestion-selected' - user selected a suggestion when alwaysRenderSuggestions={true}

onSuggestionsClearRequested (required unless alwaysRenderSuggestions={true})

This function will be called every time you need to clear suggestions.

All you have to do in this function is to set suggestions to [].

Note: When alwaysRenderSuggestions={true}, you don't have to implement this function.

getSuggestionValue (required)

When user navigates the suggestions using the Up and Down keys, the input value should be set according to the highlighted suggestion. You design how suggestion is modelled. Therefore, it's your responsibility to tell Autosuggest how to map suggestions to input values.

This function gets the suggestion in question, and it should return a string. For example:

function getSuggestionValue(suggestion) {
  return suggestion.text;
}

renderSuggestion (required)

Use your imagination to define how suggestions are rendered.

The signature is:

function renderSuggestion(suggestion, { query, isHighlighted })

where:

  • suggestion - The suggestion to render
  • query - Used to highlight the matching string. As user types in the input, query will be equal to the trimmed value of the input. Then, if user interacts using the Up or Down keys, the input will get the value of the highlighted suggestion, but query will remain to be equal to the trimmed value of the input prior to the Up and Down interactions.
  • isHighlighted - Whether or not the suggestion is highlighted.

It should return a string or a ReactElement. For example:

function renderSuggestion(suggestion) {
  return <span>{suggestion.text}</span>;
}

Important: renderSuggestion must be a pure function (we optimize rendering performance based on this assumption).

inputProps (required)

Autosuggest is a controlled component. Therefore, you MUST pass at least a value and an onChange callback to the input. You can pass any other props as well. For example:

const inputProps = {
  value, // usually comes from the application state
  onChange, // called every time the input value changes
  onBlur, // called when the input loses focus, e.g. when user presses Tab
  type: "search",
  placeholder: "Enter city or postcode"
};

inputProps.onChange (required)

The signature is:

function onChange(event, { newValue, method })

where:

  • newValue - the new value of the input
  • method - string describing how the change has occurred. The possible values are:
    • 'down' - user pressed Down
    • 'up' - user pressed Up
    • 'escape' - user pressed Escape
    • 'enter' - user pressed Enter
    • 'click' - user clicked (or tapped) on suggestion
    • 'type' - none of the methods above (usually means that user typed something, but can also be that they pressed Backspace, pasted something into the input, etc.)

inputProps.onBlur (optional)

The signature is:

function onBlur(event, { highlightedSuggestion })

where:

  • highlightedSuggestion - the suggestion that was highlighted just before the input lost focus, or null if there was no highlighted suggestion.

containerProps

Provides arbitrary properties to the outer div container of Autosuggest. Allows the override of accessibility properties.

const containerProps = {
  dataId: 'my-data-id'
  // ... any other properties
};

onSuggestionSelected (optional)

This function is called when suggestion is selected. It has the following signature:

function onSuggestionSelected(event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method })

where:

  • suggestion - the selected suggestion
  • suggestionValue - the value of the selected suggestion (equivalent to getSuggestionValue(suggestion))
  • suggestionIndex - the index of the selected suggestion in the suggestions array
  • sectionIndex - when rendering multiple sections, this will be the section index (in suggestions) of the selected suggestion. Otherwise, it will be null.
  • method - string describing how user selected the suggestion. The possible values are:
    • 'click' - user clicked (or tapped) on the suggestion
    • 'enter' - user selected the suggestion using Enter

onSuggestionHighlighted (optional)

This function is called when the highlighted suggestion changes. It has the following signature:

function onSuggestionHighlighted({ suggestion })

where:

  • suggestion - the highlighted suggestion, or null if there is no highlighted suggestion.

shouldRenderSuggestions (optional)

By default, suggestions are rendered when the input isn't blank. Feel free to override this behaviour.

This function gets the current value of the input and the reason why the suggestions might be rendered, and it should return a boolean.

For example, to display suggestions only when input value is at least 3 characters long, do:

function shouldRenderSuggestions(value, reason) {
  return value.trim().length > 2;
}

You can use the second reason argument to finely control exactly when the suggestions are rendered. The possible values are closely related to those for onSuggestionsFetchRequested, plus a few extra cases:

  • 'input-changed' - user typed something
  • 'input-focused' - input was focused
  • 'input-blurred' - input was un-focused
  • 'escape-pressed' - user pressed Escape to clear the input (and suggestions are shown for empty input)
  • 'suggestions-revealed' - user pressed Up or Down to reveal suggestions
  • 'suggestions-updated' - the suggestions were updated
  • 'render' - the component is re-rendering

When shouldRenderSuggestions returns true, suggestions will be rendered only when the input is focused.

If you would like to render suggestions regardless of whether the input is focused or not, set alwaysRenderSuggestions={true} (shouldRenderSuggestions is ignored in this case).

alwaysRenderSuggestions (optional)

Set alwaysRenderSuggestions={true} if you'd like to always render the suggestions.

Important: Make sure that the initial value of suggestions corresponds to the initial value of inputProps.value. For example, if you'd like to show all the suggestions when the input is empty, your initial state should be something like:

this.state = {
  value: "",
  suggestions: allSuggestions
};

highlightFirstSuggestion (optional)

When highlightFirstSuggestion={true}, Autosuggest will automatically highlight the first suggestion. Defaults to false.

focusInputOnSuggestionClick (optional)

By default, focusInputOnSuggestionClick={true}, which means that, every time suggestion is clicked (or tapped), the input keeps the focus.

On mobile devices, when the input is focused, the native keyboard appears. You'll probably want to lose the focus when suggestion is tapped in order to hide the keyboard.

You can do something like this:

<Autosuggest focusInputOnSuggestionClick={!isMobile} ... />

where isMobile is a boolean describing whether Autosuggest operates on a mobile device or not. You can use kaimallea/isMobile, for example, to determine that.

multiSection (optional)

By default, Autosuggest renders a plain list of suggestions.

If you'd like to have multiple sections (with optional titles), set multiSection={true}.

renderSectionTitle (required when multiSection={true})

When rendering multiple sections, you need to tell Autosuggest how to render a section title.

This function gets the section to render (an item in the suggestions array), and it should return a string or a ReactElement. For example:

function renderSectionTitle(section) {
  return <strong>{section.title}</strong>;
}

If renderSectionTitle returns null or undefined, section title is not rendered.

getSectionSuggestions (required when multiSection={true})

When rendering multiple sections, you need to tell Autosuggest where to find the suggestions for a given section.

This function gets the section to render (an item in the suggestions array), and it should return an array of suggestions to render in the given section. For example:

function getSectionSuggestions(section) {
  return section.suggestions;
}

Note: Sections with no suggestions are not rendered.

renderInputComponent (optional)

You shouldn't specify renderInputComponent unless you want to customize the rendering of the input.

To keep Autosuggest accessible, renderInputComponent MUST:

  • render an input
  • pass through all the provided inputProps to the input

Example:

const renderInputComponent = inputProps => (
  <div>
    <input {...inputProps} />
    <div>custom stuff</div>
  </div>
);

Note: When using renderInputComponent, you still need to specify the usual inputProps. Autosuggest will merge the inputProps that you provide with other props that are needed for accessibility (e.g. 'aria-activedescendant'), and will pass the merged inputProps to renderInputComponent.

renderSuggestionsContainer (optional)

You shouldn't specify renderSuggestionsContainer unless you want to customize the content or behaviour of the suggestions container beyond rendering the suggestions themselves. For example, you might want to add a custom text before/after the suggestions list, or to customize the scrolling behaviour of the suggestions container.

The signature is:

function renderSuggestionsContainer({ containerProps, children, query })

where:

  • containerProps - props that you MUST pass to the topmost element that is returned from renderSuggestionsContainer.
  • children - the suggestions themselves. It's up to you where to render them.
  • query - Same as query in renderSuggestion.

For example:

function renderSuggestionsContainer({ containerProps, children, query }) {
  return (
    <div {...containerProps}>
      {children}
      <div>
        Press Enter to search <strong>{query}</strong>
      </div>
    </div>
  );
}

When renderSuggestionsContainer returns a composite component (e.g. <IsolatedScroll ... /> as opposed to a DOM node like <div ... />), you MUST call containerProps.ref with the topmost element that the composite component renders.

For example:

import IsolatedScroll from "react-isolated-scroll";

function renderSuggestionsContainer({ containerProps, children }) {
  const { ref, ...restContainerProps } = containerProps;
  const callRef = isolatedScroll => {
    if (isolatedScroll !== null) {
      ref(isolatedScroll.component);
    }
  };

  return (
    <IsolatedScroll ref={callRef} {...restContainerProps}>
      {children}
    </IsolatedScroll>
  );
}

theme (optional)

Autosuggest comes with no styles.

It uses react-themeable that allows you to style your Autosuggest component using CSS Modules, Radium, Aphrodite, JSS, Inline styles, and global CSS.

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

/* theme.css */

.container { ... }
.input { ... }
.suggestionsContainer { ... }
.suggestion { ... }
.suggestionHighlighted { ... }
...
import theme from "theme.css";
<Autosuggest theme={theme} ... />

When not specified, theme defaults to:

{
  container:                'react-autosuggest__container',
  containerOpen:            'react-autosuggest__container--open',
  input:                    'react-autosuggest__input',
  inputOpen:                'react-autosuggest__input--open',
  inputFocused:             'react-autosuggest__input--focused',
  suggestionsContainer:     'react-autosuggest__suggestions-container',
  suggestionsContainerOpen: 'react-autosuggest__suggestions-container--open',
  suggestionsList:          'react-autosuggest__suggestions-list',
  suggestion:               'react-autosuggest__suggestion',
  suggestionFirst:          'react-autosuggest__suggestion--first',
  suggestionHighlighted:    'react-autosuggest__suggestion--highlighted',
  sectionContainer:         'react-autosuggest__section-container',
  sectionContainerFirst:    'react-autosuggest__section-container--first',
  sectionTitle:             'react-autosuggest__section-title'
}

The following picture illustrates how theme keys correspond to Autosuggest DOM structure:

DOM structure

id (required when multiple Autosuggest components 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 Autosuggest components on a page, make sure to give them unique ids. For example:

<Autosuggest id="source" ... />
<Autosuggest id="destination" ... />

Development

npm install
npm start

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

License

MIT

react-autosuggest's People

Contributors

0xjocke avatar aashishnagpal avatar aberezkin avatar adrianmcli avatar algotrader avatar andysprout avatar angelo-v avatar calebmorris avatar cheapsteak avatar dependabot[bot] avatar dkingman avatar dolomike avatar hibiken avatar hugoholgersson avatar idolize avatar jamiedixon avatar jarib avatar jstejada avatar keitamoromizato avatar kellylu29 avatar lpadier avatar moroshko avatar oyeanuj avatar pimterry avatar roiexlab avatar seropaski avatar stream7 avatar therusskiy avatar yagudaev avatar zetoke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-autosuggest's Issues

Dynamically switch suggestions-property

When I try to switch Autosuggest's suggestions-property on runTime, it seems the initial suggestions-function keeps on getting invoked instead of the new one.

How to achieve the expected behavior?

onInputSubmitted?

I'm wondering how to detect the enter key? If a user doesn't select an available option and types their own content and hits enter, can I capture that somehow? Would another event like onInputSubmitted make sense? This would fire if conditions aren't met for onSuggestionSelected when the enter key is hit.

Bug With Controlled Component Implementation

Controlled Components allow you to set value, however this effectively conflates two different concerns.
Setting the currently selected value should be equivalent to changing the selection the user has made.
Setting the currently selected inputValue should be equivalent to the user entering new text.

Currently setting value does not update the suggestion list.

What I'm really looking for is a way to simply reset the component between submissions, but there is no easy way to do this. Using the Controlled Component approach results in subtle bugs where the previous options are still displayed even when the input is blank.

Ideally I would like to either implement a "reset" functionality as an uncontrolled component or to switch the way "value" is treated as a prop and actually make it trigger a fresh search for options (or optionally to replace the value prop with 2 props. inputValue and selectedValue.

Clear auto suggest input field

Is there a way to clear the input field after a user has selected a suggestion?

I am interested in what the user has selected, and use this data to update another component but once this is done, I'd like to have access to the input so that I can clear it.

Please can you let me know if this is possible.

Thanks.

State handling

Hi,
we have encountered issue with component state. The component hold current value of input in it's internal state, so when the property inputAttributes.value is changed the change is ignored by Autosuggest component.

Here is the demo https://jsfiddle.net/1y4v9pw6/3/

The fix is remove state from component https://github.com/keboola/react-autosuggest/commit/d13008c27e2148205855b0a2fea70dfdc03eaeef and let it behave as controlled component https://facebook.github.io/react/docs/forms.html#controlled-components

Here is the demo same demo but with patched Autosuggest https://jsfiddle.net/2cuf1mzu/1/

This fix BC break, maybe also component which only holds the state could be provided for BC compatiblity.

Our use case where we discovered this issue is form where the initial value of Autosuggest component is dependent on some select value which is used before autosuggest.

Also passing a value instead of event to handler inputAttributes.onChange is bit strange.
thanks.

How do I export to standalone version.

It's not an issue but I couldn't find a suitable way to discuss this thing.

I want to convert latest release of react-autosuggest(or any other node module) to standalone version so that I can use the updated standalone library. Is there any procedure to convert node modules to one standalone script? How it is done here ?

Doesn't work with the latest React version

Hello,
I've upgraded react to 0.14.0 and react-autosuggest to 2.1.0. Now my application spews exceptions to the debug console:

Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs.
You might be adding a ref to a component that was not created inside a component's `render` 
method, or you have multiple copies of React loaded
(details: https://fb.me/react-refs-must-have-owner).

ComboBox-like behavior

Hi. I use the component with small datasets (like user roles, for example, 4-5 records) and I want to open the suggestions list with all roles in it when user clicks in the input. The getSuggestions callback already designed to return the whole list if the input arg is empty, but I can not figure out how to force the component to do this.

bootstrap

Is the themeable support usable with bootstrap? I tried briefly to configure it for bootstrap classes, but couldn't see a way to do it. For example, bootstrap wants the container for a dropdown to have class 'open' when a dropdown-menu is open, but I don't see a way to add a class to the autosuggest container when the dropdown is open.

Add option to cache case insensitive results

Scenario:

  1. User types mel
  2. Suggestions are retrieved from an API
  3. User deletes the field, and types MEL
    We should be able to reuse the previous results in cache rather hitting the API again. This should be configurable.

Input value does not update when props change

componentWillReceiveProps is not implemented. This means that the value of the input can't be set by the parent component. Quite annoying in a realtime system! I had to hack around it by setting the state directly from the parent.

Initial value is not set

I have a problem concerning the initial value, which is never set. The initial value is setted via props. Here is my Component:
module.exports = React.createClass({

getDefaultProps: function() {
return {
initial: '',
id: '',
name: '',
className: 'form-control',
placeholder: 'Chose customer...'

}

},
getInitialState: function() {
return {
CUSTOMERS: [],
initial: this.props.initial
};
},
componentWillReceiveProps: function(nextProps) {
this.fetchData();
this.setState({
initial: nextProps.initial
});
},
getSuggestions: function(input, callback) {
var customerArray = this.state.CUSTOMERS;
var regex = new RegExp('^' + input, 'i');
setTimeout(function() {
callback(null, customerArray.filter(name=> regex.test(name)));
}, 300);
},
componentWillMount: function() {
this.fetchData();
},
fetchData: function() {
var fetched = [];
$.get('/dataserveprovider/rest/data/customer/all', function(result) {
for (var i = 0; i < result.length; i++) {
fetched[i] = result[i].name;
}
});
this.setState({
CUSTOMERS: fetched
});
},
render: function() {
var inputAttributes = {
id: this.props.id,
name: this.props.name,
className: 'this.props.className',
placeholder: this.props.placeholder,
value: this.state.initial
};
return (




);
}
});

onSuggestionFocused

Hi @moroshko , I need to add event listeners for mousenter and mouseleave on my suggestions. I'm currently binding the event listener to my react component returned by suggestionRenderer, like so (simplified):

function handleMouseEnter() {
  ...
}

suggestionRenderer: function(suggestion) {
  return (
    <div onMouseEnter={handleMouseEnter}>
    ...
    </div>
  );
}

However, the event listener is never being called, and I'm getting the following react warning:
Warning: Any use of a keyed object should be wrapped in React.addons.createFragment(object) before being passed as a child.

I suspect it has to do with the current mouseenter and mouseleave event listeners which are setting the state of <Autosuggest> and causing a rerender.

Do you have any thoughts on the exact cause of this, or any workarounds? Do you think you could support an option like onSuggestionMouseEnter, or maybe something like onSuggestionFocused to account for the key up and key down events as well? Sort of like how onSuggestionSelected works.

Thanks!!

Scaling?

Any idea how this performs with list of 2,000 entries? 5,000?

How import another component with a company list?

I have a company list:
import CompanyList from 'Company/List/CompanyList';

import css from './SearchField.styl';
import React, { Component } from 'react';

import Svgo from 'Element/Svgo/ElementSvgo';
import CN from 'classnames';
import Select from 'react-select';
import CompanyList from 'Company/List/CompanyList';
import Autosuggest from 'react-autosuggest';

const suburbs = ['Cheltenham', 'Mill Park', 'Mordialloc', 'Nunawading'];
import { getCompanies } from 'actions/CompanyActions';

import CompanyPanel from 'Company/Panel/CompanyPanel';

export default class SearchInput extends Component {

render() {

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

}

return (

  <div className={CN(css.selectLive)}>
    <Autosuggest suggestions={getSuggestions} />
  </div>
);

}
};

No Results feedback

It would be nice being able to give the user feedback in case there's no result found.

Order of execution of onSuggestionSelected option

I have a use case where I need the function I pass in as the onSuggestionSelected option to be called after the autosuggest has completely re-rendered the list of suggestions, i.e. after it has successfully removed/cleared the list of suggestions.

@moroshko , do you think this would be a good idea to implement?

Feature request: easy clearing of value after a selection has been made

I have looked through some of the issues that seem to have to do with this scenario, but none of them seemed to give a very easy way to clear the value in the input, from what I could see.

Maybe implement a public reset() method that can be called from the onSuggestionSelected in situations where the callback is running in the parent component? This makes a lot of sense in applications where you are entering a value, pressing down arrow and hitting enter and then are expected to proceed to type another value and repeat the process again.

This would match very well with the first example under Benefits at https://facebook.github.io/react/docs/more-about-refs.html#benefits

If there already is an easy way to do this, I most certainly will accept pointers in the right direction as well.

Using another input element?

Is there an option where I can refer to another input element? Because our app relies heavily on react-bootstrap which comes with a nice set of predefined inputs.

To avoid ugly hacks or forks, it would be nice if this module would accept a reference to another existing input. Does such an option already exist or do you think you could add that?

setting the type of the input

Is it possible to set the type of the input? For example, setting input type=search, creates an automatic "clear" button which is pretty useful.

Best practice to show up value different from the internal

For example, I have a suggestions with the following JSON:

[
  {"name": "John", "id": 1},
  {"name": "James", "id": 2}
]

How would I show up the John as a selected suggestion, but use 1 (id) as a value to post with a form?

I can think of only one solution, hide input with a id value, and show name in span or div tag.

How do you deal with following situations?

need cursor position to generate suggestions

For multi-word inputs the cursor position is necessary for generating the list of suggestions. This might be accomplished by passing it in the suggestions callback, by passing the ref for the input element, or by exposing the refs on the AutoSuggest class so the caller can inspect the cursor position.

focus?

Question: Why re-implement focus, instead of using the browser built-in focus? And if re-implementing, why call it "focus", when that already means something else? It is very confusing that onSuggestionFocused is unrelated to the browser focus.

accessiblity feature: scroll focused suggestion into view

It would be great, if the focused suggestion could use scrollIntoView so that we could ensure it was visible.

Two options I can see for how to implement this:

  1. onSuggestionFocused could pass the full focus event as a second parameter so that users could use DOM APIs to implement this themselves.
  2. Just have this lib call scrollIntoView on focus.

React version compatibility

Does this component absolutely need the latest version of React in order to work properly? If not, its package.json should allow for older versions of React as far back as it will still work, while still trying to use the latest one possible. Otherwise, trying to use this component in conjunction with other components that need older versions of React results in a conflict of peer dependencies.

Package dist as single file for client-side inclusion

I'm using Meteor which doesn't allow importing NPM packages on the client-side - is it possible to get this packaged into a single file for client-side inclusion.

I'm trying to hack a solution up in Webpack/Browserify now...

Thanks :)

Need to disable caching

Hi! The forced caching solution looks strange for many reasons and breaks desired behavior of the component. Could you please add an option to disable it?

onBlur event on the input

Hello,
Is there any way to trigger onBlur on the input box ?

i've tried this:

  1. in the render function
       const inputAttr = {
            id: 'someID',
            name: 'someName',
            placeholder: 'somePlaceholder',
            onBlur: this.blurCallback
        };

in component:

   blurCallback: function(evt){
     console.log('something', e);
   },

the method called "blurCallback" is not triggered when i'm defocusing the input box.
Anyone can give me some hints on this issue ? am i missing something ? or this isn't implemented in moroshko's component?

thanks

Suggestions list via props instead of callback for flux data flow?

Is there any way of doing this? I really like the component because it's the easiest autocomplete I tried, looks great, and has full ARIA support - lots of things to like!

What would be even better is a lightweight version that simply takes in the suggestions as a prop, but everything else remains as is. I originally tried putting a flux action call in the suggestions function, but since fluxible returns the results of actions onto props, I didn't have a good way of calling the callback after the props became available. I was trying to fool around in the source a bit to see if I could get it working but didn't quite get there... is this something you would think about adding in the future? For now I'm adding my calls to the server directly into the component, but I'd really like to take those out in the future.

Thanks!

React to enter press when nothing is selected

I have following values available for autosuggest:

  • value 1
  • value 2
  • value 3

Now, without doing any selection with arrows or mouse, I want to type "value 1" and hit enter. Currently, I can't seem to get any callback on this. Am I missing something?

Disabled options

I'd like to have some disabled options. Anyone know how I could add that functionality?

I could use suggestion objects with a disabled property. However, I'll need a way of attaching a special css class to each disabled item. Also, I'll need to prevent the default behaviour on focus for disabled items.

autofocus support?

Hi, how I can add autofocus to input field?

I've tried something like:

 <Autosuggest                                                          
              inputAttributes={{                                                  
               value: this.state.query || '',                                    
               autofocus: true,                                                  
               placeholder: this.props.placeholder}}                              
               suggestions={this.props.on_get_suggestions}/> 

but does not work.

Dropdown without input value

We'd love to be able to dropdown the suggestions on input focus even when there's no value. Looking through the source, it seems that might be impossible at the moment - is that the case?

Dropdown closes on focus lost, but does not re-open on focus gained

Specifically the way this manifests is when I switch to a different window and return the dropdown should re-open. Instead I end up in a state where the textbox has text and is selected but the dropdown is not open.

The component should listen to onfocus and re-open.

closeOnSelect or selectMultiple option

hi @moroshko ! me again.

I was wondering what you thought of an option to prevent the Autosuggest from closing when a suggestion is selected. This would allow users to select more than one suggestion, and I believe it might be a common use case.

Let me know what you think. Thanks!

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.