{{announcement.body}}
{{announcement.title}}

How To Add AutoComplete Textbox In React Application

DZone 's Guide to

How To Add AutoComplete Textbox In React Application

In this article we are going to learn how we add AutoComplete textbox in ReactJS. We use Material UI Autocomplete component in this demo.

· Web Dev Zone ·
Free Resource

Introduction

In this article, we are going to learn how we add the AutoComplete textbox in ReactJS. We use the 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.

You may also like: An Angular Autocomplete From UI to DB

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".

Java




x


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 = ON) ON [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.

microsoft visual studios

Change the name to Autocomplete. 

microsoft visual studios

Choose the template as Web API.

microsoft visual studios

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.

microsoft visual studios

Click on the "ADO.NET Entity Data Model" option and click "Add".

microsoft visual studios

Select EF Designer from the database and click the "Next" button.

microsoft visual studios

Add the connection properties and select database names on the next page and click OK.

microsoft visual studios

Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button

microsoft visual studios

Now, our data model is successfully created.  

Right-click on the Controller folder and add a new controller. Name it as an "Autocomplete controller" and add the following namespace in the Autocomplete controller.

C#


Now add a method to fetch data from the database.

Java


Complete Autocomplete controller code

C#




xxxxxxxxxx
1
22


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.

Java




xxxxxxxxxx
1


1
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");          
2
config.EnableCors(cors); 



Create ReactJS Project

 Now let's first create a React application with the following command.

C#




xxxxxxxxxx
1


1
npx create-react-app autocomplete 



Open the newly created project in the Visual Studio Code and install Material-UI

Install Material-UI

 Now install Material-UI by using the following command

JavaScript




xxxxxxxxxx
1


 
1
npm install @material-ui/core --save   



Now install the Axios library by using the following command. Learn more about Axios.

Java




xxxxxxxxxx
1


1
npm install --save axios  



Now go to the src folder and add new components.

Autocomplete.js 

Now open the Autocomplete.js  component and import the required reference.

JavaScript




xxxxxxxxxx
1


1
import Autocomplete from '@material-ui/lab/Autocomplete';  
2
import AppBar from '@material-ui/core/AppBar';  
3
import Toolbar from '@material-ui/core/Toolbar'; 



The following code in this component.

Java




xxxxxxxxxx
1
47


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 the app.cs file and add the following code.

Java




xxxxxxxxxx
1


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 the following code.

Java




xxxxxxxxxx
1
14


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',

Did you find this article helpful? Let us know in the comments!


Further Reading

Create an ASP.NET MVC AutoFill Control, Part 1

Fun With React: A Quick Overview

Everything React: Tutorials for Beginners and Experts Alike

Topics:
reactjs ,web api ,sql server ,tutorial ,web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}