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.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
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".
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 names 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 Controller folder and add a new controller. Name it as an "Autocomplete controller" and add the following namespace in the Autocomplete controller.
using AutoComplete.Models;
Now add a method to fetch data from the database.
xxxxxxxxxx
public object Getrecord()
{
var data= DB.TblCountries.ToList();
return data;
}
Complete Autocomplete controller code
xxxxxxxxxx
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.
xxxxxxxxxx
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Create ReactJS Project
Now let's first create a React application with the following command.
xxxxxxxxxx
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
xxxxxxxxxx
npm install @material-ui/core --save
Now install the Axios library by using the following command. Learn more about Axios.
xxxxxxxxxx
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.
xxxxxxxxxx
import Autocomplete from '@material-ui/lab/Autocomplete';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
The following code in this component.
xxxxxxxxxx
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 the app.cs file and add the following code.
xxxxxxxxxx
.mrg{
margin-top: 20px;
margin-bottom: 20px;
}
.pding
{
padding-left: 500px;
}
Now open app.js file and add the following code.
xxxxxxxxxx
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',
Did you find this article helpful? Let us know in the comments!
Further Reading
Opinions expressed by DZone contributors are their own.
Comments