Search Autocomplete

This is a basic example of search auto-complete which uses onChange event and fetches the suggested resultant values.


Example Project Search Autocomplete

To create the example project for this example, open command prompt, navigate to a convenient location, and run the command as shown below :

create-react-app example4

Create two new files AutoCompletedText.js and Countries.js add the below content and replace the placeholder content of App.js and App.css with given below content :


src\AutoCompletedText.js

import React from 'react';
import countries from './Countries';
import './App.css';

export default class AutoCompletedText extends React.Component{

    constructor(props){
        super(props)
        this.state = {
            suggestions: [],
            text: ''
        }
    }

    onTextChange = (e) => {
        const value = e.target.value;
        let suggestions = [];
        if(value.length > 0){
            const regex = new RegExp(`^${value}`, 'i');
            suggestions = countries.sort().filter(v => regex.test(v))
        }

        this.setState(() => ({
            suggestions,
            text: value
        }))
    }

    selectedText(value) {
        this.setState(() => ({
            text: value,
            suggestions: [],
        }))
    }

    renderSuggestions = () => {
        let { suggestions } = this.state;
        if(suggestions.length === 0){
            return null;
        }
        return (
            <ul >
                {
                    suggestions.map((item, index) => (<li key={index} onClick={() => this.selectedText(item)}>{item}</li>))
                }
            </ul>
        );
    }
    
    render() {
        const { text, suggestions } = this.state;
        return(
            <div id="notebooks">
                <h2>Auto Completed</h2>
                <input id="query" type="text" onChange={this.onTextChange} value={text}/>
                {this.renderSuggestions()}
                <span>Suggestions: {suggestions.length}</span>
            </div>
        );
    }

}

src\Countries.js

export default `
Afghanistan
Albania
Algeria
Andorra
Angola
Antigua & Deps
Argentina
Armenia
Australia
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belgium
Belize
Benin
Bhutan
Bolivia
Bosnia Herzegovina
Botswana
Brazil
Brunei
Bulgaria
Burkina
Burundi
Cambodia
Cameroon
Canada
Cape Verde
Central African Rep
Chad
Chile
China
Colombia
Comoros
Congo
Congo {Democratic Rep}
Costa Rica
Croatia
Cuba
Cyprus
Czech Republic
Denmark
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Fiji
Finland
France
Gabon
Gambia
Georgia
Germany
Ghana
Greece
Grenada
Guatemala
Guinea
Guinea-Bissau
Guyana
Haiti
Honduras
Hungary
Iceland
India
Indonesia
Iran
Iraq
Ireland {Republic}
Israel
Italy
Ivory Coast
Jamaica
Japan
Jordan
Kazakhstan
Kenya
Kiribati
Korea North
Korea South
Kosovo
Kuwait
Kyrgyzstan
Laos
Latvia
Lebanon
Lesotho
Liberia
Libya
Liechtenstein
Lithuania
Luxembourg
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Mauritania
Mauritius
Mexico
Micronesia
Moldova
Monaco
Mongolia
Montenegro
Morocco
Mozambique
Myanmar, {Burma}
Namibia
Nauru
Nepal
Netherlands
New Zealand
Nicaragua
Niger
Nigeria
Norway
Oman
Pakistan
Palau
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Poland
Portugal
Qatar
Romania
Russian Federation
Rwanda
St Kitts & Nevis
St Lucia
Saint Vincent & the Grenadines
Samoa
San Marino
Sao Tome & Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Singapore
Slovakia
Slovenia
Solomon Islands
Somalia
South Africa
South Sudan
Spain
Sri Lanka
Sudan
Suriname
Swaziland
Sweden
Switzerland
Syria
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tonga
Trinidad & Tobago
Tunisia
Turkey
Turkmenistan
Tuvalu
Uganda
Ukraine
United Arab Emirates
United Kingdom
United States
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Yemen
Zambia
Zimbabwe`.split('\n')

src\App.js

import React, { Component } from 'react';
import AutoCompletedText from './AutoCompletedText';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <AutoCompletedText />
      </div>
    );
  }
}

export default App;

src\App.css

.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 40vmin;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
li {
    list-style: none;
    background-color: rgba(0, 0, 0, 0.05);
    background-image:
        linear-gradient(90deg,
        #FFD32E 10px,
        #EEE 10px,
        #EEE 11px,
        transparent 11px);
    padding: 10px 15px 10px 25px;
    border: 1px solid #CCC;
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, 0.5);
    margin-bottom: 5px;
    width: 100%;
    box-sizing: border-box;
    cursor: pointer;
    border-radius: 3px;
}

#query {
    width: 100%;
    box-sizing: border-box;
    font-size: 19px;
    padding: 5px;
    font-family: calibri light;
    margin-bottom: 10px;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 3px;
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, 0.1);
}

#notebooks {
    background: whitesmoke;
    position: absolute;
    left: 50%;
    margin-left: -175px;
    margin-top: 35px;
    width: 350px;
    padding: 15px;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 5px;
    box-shadow: inset 1px 1px 0 white;
    max-height: 450px;
}

ul {
    margin: 0 auto;
    padding: 0;
    max-height: 390px;
    overflow-y: auto;
    border: 1px solid rgba(0, 0, 0, 0.1);
    padding: 5px 5px 0 5px;
    border-left: none;
    border-right: none;
}

#notebooks span {
    display: block;
    position: absolute;
    background: #FFD32E;
    bottom: -35px;
    left: -1px;
    width: 360px;
    border-radius: 0 0 5px 5px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    padding: 10px;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: inset 1px 1px rgba(255, 255, 255, 0.5);
}


Most Helpful This Week