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".
- CREATE TABLE [dbo].[TblCountry](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- CONSTRAINT [PK_TblCountry] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
Now add some demo data in this table.
Create a new Web API project
Open Visual Studio and create a new project.
Change the name to Autocomplete.
Choose the template as Web API.
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
Click on the "ADO.NET Entity Data Model" option and click "Add".
Select EF Designer from the database and click the "Next" button.
Add the connection properties and select database name on the next page and click OK.
Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button
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.
- using AutoComplete.Models;
Now add a method to fetch data from database.
- public object Getrecord()
- {
- var data= DB.TblCountries.ToList();
- return data;
- }
Complete Autocomplete controller code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using AutoComplete.Models;
- namespace AutoComplete.Controllers
- {
- [RoutePrefix("Api/autoComplete")]
- public class AutoCompleteController : ApiController
- {
- AutoCompleteEntities2 DB = new AutoCompleteEntities2();
- [HttpGet]
- [Route("Countrylist")]
- public object Getrecord()
- {
- var data= DB.TblCountries.ToList();
- return data;
- }
- }
- }
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.
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
Create ReactJS project
Now let's first create a React application with the following command.
- 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
- npm install @material-ui/core --save
Now install the Axios library by using the following command. Learn more about
Axios
Now go to src folder and add new components.
Autocomplete.js
Now open Autocomplete.js component and import required reference.
- import Autocomplete from '@material-ui/lab/Autocomplete';
- import AppBar from '@material-ui/core/AppBar';
- import Toolbar from '@material-ui/core/Toolbar';
Add the following code in this component.
- import React, { Component } from 'react';
- import TextField from '@material-ui/core/TextField';
- import Autocomplete from '@material-ui/lab/Autocomplete';
- import AppBar from '@material-ui/core/AppBar';
- import Toolbar from '@material-ui/core/Toolbar';
- import './App.css';
- import axios from 'axios';
- export class Autocom extends Component {
- constructor(props) {
- super(props)
- this.state = {
- ProductData: []
-
- }
- }
- componentDidMount() {
- axios.get('http://localhost:51983/Api/autoComplete/Countrylist').then(response => {
- console.log(response.data);
- this.setState({
- ProductData: response.data
- });
- });
- }
- render() {
-
- return (
- <div>
- <AppBar className="mrg" position="static">
- <Toolbar >
- Auto Complete
- </Toolbar>
- </AppBar>
- <Autocomplete className="pding"
- id="combo-box-demo"
- options={this.state.ProductData}
- getOptionLabel={option => option.Name}
- style={{ width: 300 }}
- renderInput={params => (
- <TextField {...params} label="Auto Complete" variant="outlined" fullWidth />
- )}
- />
- </div>
- )
- }
-
- }
- export default Autocom
Now open app.cs file and add the following code.
-
- .mrg{
- margin-top: 20px;
- margin-bottom: 20px;
- }
- .pding
- {
- padding-left: 500px;
- }
Now open app.js file and add following code
- import React from 'react';
- import logo from './logo.svg';
- import './App.css';
- import Form from './Form'
- import Autocom from './Autoc'
- function App() {
- return (
- <div className="App">
- <Autocom/>
- </div>
- );
- }
-
- export default App;
Now run the project by using 'npm start',
Summary
In this article, we learned how we add autocomplete textbox in reactjs applications.