Autocomplete input using React

Introduction

I am going to show you how to show auto complete suggestion when users search for something by typing in the input field.

Autocomplete allows users to have other suggested strings or values displayed on typing of the relevant text in the input field.

You have also seen when you start a search on Google or other search engines, you can find the information you are looking for using search predictions.

Search predictions are possible search terms you can use that are related to the terms you are typing and what other people are searching for.

Autocomplete is a feature in which an application predicts the rest of a word a user is typing. In graphical user interfaces, users can typically press the tab key to accept a suggestion or the down arrow key to accept one of several.

Autocomplete speeds up human-computer interactions when it correctly predicts the word a user intends to enter after only a few characters have been typed into a text input field. The autocomplete is a normal text input enhanced by a panel of suggested options.

Prerequisites

React

How to create React Project

Implement Autocomplete

Here we are going to show you how to implement auto complete input field suggestion.

Once you create React JS application, you need to edit the file src/App.js.

I am also going to show you how to load static JSON data into React application. We are using this static data to show the search results for the matched input string.

I am also using inline css style to remove bullets from the unordered list.

I am going to use <React-Fragment/> to parse the HTML tags.

Upload results.json file under data folder under src folder. The data or search results show come from daatabase or external system.

[
	"Lorem Ipsum is simply dummy text of the printing and typesetting",
	"Lorem Ipsum has been the industry's standard dummy",
	"nd scrambled it to make a type specimen book. It",
	"typesetting, remaining essentially unchanged. It ",
	"sum passages, and more recently with desktop publi",
	"Contrary to popular belief, Lorem Ipsum is not sim",
	"professor at Hampden-Sydney College in Virginia, looked up one",
	"passage, and going through the cites of the word in",
	"comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum",
	"BC. This book is a treatise on the theory of ethics, very popu",
	"here are many variations of passages of Lorem Ipsum availa",
	"believable. If you are going to use a passage of Lorem Ips",
	"middle of text. All the Lorem Ipsum generators on the Intern",
	"tend to repeat predefined chunks as necessary, making this the",
	"first true generator on the Internet. It uses a dictionary of over 20",
	"he standard chunk of Lorem Ipsum used since the 1500s i",
	"1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are als",
	"reproduced in their exact original form, accompanied by English",
	"eadable content of a page when looking at its layout. The point"
]

Change page title by editing the file public/index.html:

<title>Auto complete input using React</title>

The code shown below has the actual implementation. Using JavaScript’s on key up event we are showing suggested texts.

Edit App.js file under src directory and change as below:

import React from 'react';
import json from './data/results.json';

class AutoCompleteApp extends React.Component {
	constructor(props) {
		super(props);
		this.state = { suggestions:[] };
		this.search = this.search.bind(this);
	}
	
	search(event) {
		let input = event.target.value;
		//console.log('event.target.value: ' + input);
		//console.log('this.searchResults: ' + json);
		let matches = [], i;
		
		if (input.length > 1) {
			for (i = 0; i < json.length; i++) {
				if (json[i].match(input)) {
					matches.push(json[i]);
				}
			}
		}
		
		this.setState({ suggestions: matches });
	}

	render() {
		return (
			<div>
				<label>Search Here</label>&nbsp;&nbsp;<input onKeyUp={this.search.bind(this)}/> 
				<React.Fragment>
					<ul style={{listStyleType:'none'}}>
						{this.state.suggestions.map(res => (
							<li key={res}>
								{res}
							</li>
						))}
					</ul>
				</React.Fragment>
			</div>
		);
	}
}

export default AutoCompleteApp;

We don’t want to show bullets to the list style, so we have applied listStyleType to none.

Testing the Application

Execute command npm start on project’s root directory and your application will automatically open at http://localhost:3000.

You will see an input search box. Typing something will return you results if found. For example, if you type he, then it will return below results:

autocomplete input using react

Source Code

Download

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *