Skip to content

Ambisafe/react-async-autocomplete

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Async Autocomplete

This autocompleter will display options and react to keypress (up, down, enter, esc). Inspired in React Autocomplete, but designed for a simplified workflow where requests are expected to be asynchronous (synchronous is supported, but should be less common) and will display a loading icon.

Check the demo here.

Use

import Autocomplete from "react-async-autocomplete";

// render one item on the list
const MyItemView = function({ user }) {

  return (
    <div className="user-data">
      <div>{user.id}</div>
      <div>{user.name}</div>
    </div>
  );

} 

class MyApp extends React.Component {

  constructor() {
    super();
    this.state = {
      selected: undefined
    }
    this.onChange = this.onChange.bind(this);
    this.onSelect = this.onSelect.bind(this);
  }

  // invoked when the user types something. A delay of 200ms is 
  // already provided to avoid DDoS'ing your own servers
  onChange(query) {
    
    // you would normally do here your server access
    fetch('/users/search?q=' + query)
    .then((result) {
      this.refs.autocomplete.setItems(result.body);
    })
  }

  // called when the user clicks an option or hits enter
  onSelect(user) {
    this.setState({
      selectedUser: user
    });
    // the returned value will be inserted into the input field. 
    // Use an empty String to reset the field
    return user.getName();
  }

  render() {
    return (
      <div>
        <Autocomplete 
          ref="autocomplete"
          ItemView={MyItemView} 
          onChange={this.onChange} 
          onSelect={this.onSelect}
        />
      </div>
    )
  }

};

Releases

No releases published

Packages

No packages published

Languages

  • CSS 96.5%
  • JavaScript 3.1%
  • HTML 0.4%