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

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.

Now add a method to fetch data from the database.

Complete Autocomplete controller code

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.

Create ReactJS Project

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

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

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

Now go to the src folder and add new components.

Autocomplete.js 

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

The following code in this component.

Now open the app.cs file and add the following code.

Now open app.js file and add the following code.

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



Source link

Write A Comment