Create a Cascading Dropdown in ReactJS
Join the DZone community and get the full member experience.Join For Free
In this article, we will learn how to create a cascading dropdown using ReactJS and Web API. A cascading dropdown is a group of dropdowns where the value of one dropdown depends upon another dropdown value. Child dropdown values are populated based on the item selected in the parent dropdown.
- We should have 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.
- Basic knowledge of Bootstrap and HTML.
You may also like: Everything React: Tutorials for Beginners and Experts Alike.
Create a Table in the Database
Open SQL Server Management Studio, create a database named "CascadingDemo", and in this database, create three tables and some demo data in the tables:
Create a New Web API Project
Open Visual Studio and create a new project.
Change the name to CascadingDemo.
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 OK
Now, our data model is successfully created.
Right-click on the Controllers folder and add a new controller. Name it "CascadingDemo controller" and add the following namespace in the CascadingDemo controller.
Now, add three methods to get country, state, and city data from the database.
Complete CascadingDemo 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 a ReactJS Project
Now, let's first create a React application with the following command.
Install Bootstrap by using the following commands.
Open the index.js file and add import Bootstrap.
Install the Axios library by using the following command. Learn more about Axios.
Now go to the src folder and add a new component, named "Cascading.js", and add the following code.
Add a reference of this component in your app.js file, and add the following code in the app.js file.
Now, open the app.css file and add the following CSS classes:
Now run the project and select country value from the country dropdown, based on country state dropdown filled in.
Now, select state and city in subsequent dropdowns.
In this article, we learned how to create cascading dropdowns using ReactJS and Web API. Child dropdown values are populated based on the item selected in the parent dropdown.
Opinions expressed by DZone contributors are their own.