How To Add AutoComplete Textbox In React Application

Introduction

 
In this article we are going to learn how we add AutoComplete textbox in ReactJS. We use Material UI Autocomplete component in this demo.
 
Prerequisites
  • We should have the basic knowledge of React.js and Web API.
  • Visual Studio and Visual Studio Code IDE should be installed on your system.
  • SQL Server Management Studio
  • Material UI Installed

Create a table in the database

 
Open SQL Server Management Studio, create a database named "Autocomplete", and in this database, create a table. Give that table a name like "Tblcountry".
  1. CREATE TABLE [dbo].[TblCountry](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [Name] [nvarchar](50) NULL,    
  4.  CONSTRAINT [PK_TblCountry] PRIMARY KEY CLUSTERED     
  5. (    
  6.     [Id] ASC    
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  8. ON [PRIMARY]    
  9. GO     
Now add some demo data in this table.
 

Create a new Web API project

 
Open Visual Studio and create a new project.
 
How To Add AutoComplete Textbox In React Application
 
Change the name to Autocomplete. 
 
How To Add AutoComplete Textbox In React Application
 
Choose the template as Web API.
 
How To Add AutoComplete Textbox In React Application
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
How To Add AutoComplete Textbox In React Application
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
How To Add AutoComplete Textbox In React Application
 
Select EF Designer from the database and click the "Next" button.
 
How To Add AutoComplete Textbox In React Application
 
Add the connection properties and select database name on the next page and click OK.
 
How To Add AutoComplete Textbox In React Application
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button
 
How To Add AutoComplete Textbox In React Application
 
Now, our data model is successfully created.  
 
Right-click on the Controllers folder and add a new controller. Name it as "Autocomplete controller" and add the following namespace in the Autocomplete controller.
  1. using AutoComplete.Models; 
Now add a method to fetch data from database.
  1. public object Getrecord()  
  2. {  
  3.    var data= DB.TblCountries.ToList();  
  4.    return data;  

 Complete Autocomplete controller code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using AutoComplete.Models;  
  8. namespace AutoComplete.Controllers  
  9. {  
  10.     [RoutePrefix("Api/autoComplete")]  
  11.     public class AutoCompleteController : ApiController  
  12.     {  
  13.           AutoCompleteEntities2 DB = new AutoCompleteEntities2();  
  14.             [HttpGet]  
  15.             [Route("Countrylist")]  
  16.             public object Getrecord()  
  17.             {  
  18.              var data= DB.TblCountries.ToList();  
  19.              return data;  
  20.             }  
  21.         }  
  22.     } 
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");          
  2. config.EnableCors(cors); 

Create ReactJS project

 
Now let's first create a React application with the following command.
  1. npx create-react-app autocomplete 
Open the newly created project in Visual Studio Code and install Material-UI. 
 

Install Material-UI

 
Now install Material-UI by using the following command
  1. npm install @material-ui/core --save   
Now install the Axios library by using the following command. Learn more about Axios
  1. npm install --save axios    
Now go to src folder and add  new components.
 
Autocomplete.js 
 
Now open Autocomplete.js  component and import required reference.
  1. import Autocomplete from '@material-ui/lab/Autocomplete';  
  2. import AppBar from '@material-ui/core/AppBar';  
  3. import Toolbar from '@material-ui/core/Toolbar';  
Add the following code in this component.
  1. import React, { Component } from 'react';  
  2. import TextField from '@material-ui/core/TextField';  
  3. import Autocomplete from '@material-ui/lab/Autocomplete';  
  4. import AppBar from '@material-ui/core/AppBar';  
  5. import Toolbar from '@material-ui/core/Toolbar';  
  6. import './App.css';  
  7. import axios from 'axios';  
  8. export class Autocom extends Component {  
  9.         constructor(props) {  
  10.                 super(props)  
  11.                 this.state = {  
  12.                         ProductData: []  
  13.   
  14.                 }  
  15.         }  
  16.         componentDidMount() {  
  17.                 axios.get('http://localhost:51983/Api/autoComplete/Countrylist').then(response => {  
  18.                         console.log(response.data);  
  19.                         this.setState({  
  20.                                 ProductData: response.data  
  21.                         });  
  22.                 });  
  23.         }  
  24.         render() {  
  25.   
  26.                 return (  
  27.                         <div>  
  28.                                 <AppBar className="mrg" position="static">  
  29.                                         <Toolbar >  
  30.                                                 Auto Complete  
  31.  </Toolbar>  
  32.                                 </AppBar>  
  33.                                 <Autocomplete className="pding"  
  34.                                         id="combo-box-demo"  
  35.                                         options={this.state.ProductData}  
  36.                                         getOptionLabel={option => option.Name}  
  37.                                         style={{ width: 300 }}  
  38.                                         renderInput={params => (  
  39.                                                 <TextField {...params} label="Auto Complete" variant="outlined" fullWidth />  
  40.                                         )}  
  41.                                 />  
  42.                         </div>  
  43.                 )  
  44.         }  
  45.   
  46. }  
  47. export default Autocom  
Now open app.cs file and add the following code.
  1.  
  2. .mrg{  
  3.   margin-top: 20px;  
  4.   margin-bottom: 20px;  
  5. }  
  6. .pding  
  7. {  
  8.   padding-left: 500px;  
  9. }  
Now open app.js file and add following code
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import Form from './Form'  
  5. import Autocom from './Autoc'  
  6. function App() {  
  7.   return (  
  8.     <div className="App">  
  9.       <Autocom/>  
  10.     </div>  
  11.   );  
  12. }  
  13.   
  14. export default App;  
Now run the project by using 'npm start',
 
How To Add AutoComplete Textbox In React Application

Summary

 
In this article, we learned how we add autocomplete textbox in reactjs applications.


Similar Articles