A ReactJS Component That integrates Twitter's Typeahead Autosuggest Control

A ReactJS Component That integrates Twitter's Typeahead Autosuggest Control

A stylish and flexible reactJS autosuggest component that integrates Twitter's typeahead.js with ReactJS. Typeahead.js was built by Twitter and is one of the most frequently used and trusted solutions for a battle-tested autosuggest control.

React-Twitter-Typeahead

A stylish and flexible reactJS autosuggest component that integrates Twitter's typeahead.js with ReactJS. Typeahead.js was built by Twitter and is one of the most frequently used and trusted solutions for a battle-tested autosuggest control.

The preview below showcases configuring this component for searching against google books using a custom template.

See some examples on our Azure site

Installation

git clone https://github.com/erikschlegel/React-Twitter-Typeahead.git
cd React-Twitter-Typeahead
npm install
npm run build

Usage

Let's start off creating a basic typeahead by customizing the bloodhound config object. Bloodhound is typeahead.js's powerful suggestion engine. The API docs that explain the available options in the bloodhound config object are here.

var React = require('react');
var ReactTypeahead = require('./lib/js/react-typeahead');
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California';//....

var bloodhoundConfig = {
    local: states
};

React.render(
    <ReactTypeahead bloodhound={bloodhoundConfig} 
                    placeHolder="States - A basic example"/>,
    document.getElementById('#typeaheadDiv')
);

You can also configure the component to make a JSONP remote call and dress up the results by using a handlebar custom template.

Configuring the remote call

Bloodhound allows you to transform the returned response prior to typeahead.js processing(var responseTransformation). In the example below we're extracting the data points from the response that are relevant for rendering. The URL call can be configured in the 'remote' object of the bloodhound config. All other available options are listed in Twitter's API docs.

var responseTransformation = function(rsp){
      var initRsp = rsp.items, maxCharacterTitleLgth = 29, maxDescLength = 80;
      var finalResult = [];

      initRsp.map(function(item){
          var title = item.volumeInfo.title;
          finalResult.push({value: title.length>maxCharacterTitleLgth?title.substring(0, maxCharacterTitleLgth):title,
                            thumbnail: item.volumeInfo.imageLinks.thumbnail,
                            id: item.id,
                            description:(item.volumeInfo.description)?item.volumeInfo.description.substring(0, maxDescLength):''});
      });

      return finalResult;
};

var bloodhoundRemoteConfig = {
  remote: {
    url: 'https://www.googleapis.com/books/v1/volumes?q=%QUERY',
    wildcard: '%QUERY',/*typeahead.js will replace the specified wildcard with the inputted value in the GET call*/
    transform: responseTransformation
  }
};

Adding some style

You can customize the presentation of the remote dataset by overriding the dataset config. All available options are listed here. This project comes packaged with handlebars, but you're free to use your template library of choice.

var Handlebars = require('handlebars');

var datasetConfig = {
  name: 'books-to-buy',
  display: 'value',
  limit: 8,
  templates: {
    header: header,
    pending: '<div style="padding-left:5px;">Processing...</div>',
    empty: '<div>unable to find any books that matched your query</div>',
    suggestion: Handlebars.compile(handlerbarTemplate)
  }
};

Binding Custom Events

Custom callbacks can be provided in the customEvents config. This sample callback is invoked when you select an option in the dropdowan. 'id' is a property on the returning dataset. All other optional callback functions can be found in the docs.

var selectedFunc = function(e, datum){alert('Selected book: ' + datum['id']);};
var customEvents = {
  'typeahead:selected typeahead:autocompleted': selectedFunc
};

Brining it all together with some additional typeahead configuring

var typeaheadConfig = {highlight:false};

React.render(
    <ReactTypeahead bloodhound={bloodhoundRemoteConfig} 
                    datasource={datasetConfig}
                    customEvents = {customEvents}
                    typeahead={typeaheadConfig}
                    placeHolder="A remote call + custom template" />,
    document.getElementById('#typeaheadDivRpc')
);

Dependencies

This requires NPM. Also, the underlying typeahead.js library uses jquery to hook some initial events to the control, so you'll need to include the following scripts towards the end of your html page.

    <script src="../vendor/jquery/jquery.js"></script>
    <script src="../vendor/typeahead.js/typeahead.bundle.js"></script>

Download Details:

Author: erikschlegel

Demo: http://reactypeahead.azurewebsites.net/example/

Source Code: https://github.com/erikschlegel/React-Twitter-Typeahead

react reactjs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Increase Performance of React Applications Via Array JavaScript Methods

Increase Performance of React Applications Via Array JavaScript Methods. We will create a simple event management application in the react to add, update, and delete an event.

Routing in React without React-Router

I have been using React JS in my projects for quite some time now and am used to managing routing in my app using the react-router package. I have always been keen on having as little dependencies in my apps as possible, so, I always felt perturbed by the use of this particular package in simpler apps which did not have complex routes.

The Ugly Side of React Hooks

In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.

ReactJS: The Javascript Developer’s Guide

This article will walk you through the concepts you would need to know to step into the world of widely used ReactJS.