Cascading Dropdown in React
Today we will create a cascading dropdown in React. In other words, we can also say that the dependent dropdown.
What is cascading dropdown?
Cascading dropdown is nothing but a list of the dropdowns where the value of the one dropdown is depends upon another dropdown. So the child dropdown list is generated based on the selection of the parent dropdown.
Let’s create a React demo where we will use the sample JSON data to implement the cascading dropdown of the Country & Language where language list will be based on the selected country. You can also create an example of the Country, State and City dropdowns based on the given logic.
Steps to implement cascading dropdown in React
- Create a react app
- Add react-select npm package
- Use sample JSON data
- Add logic to implement cascading dropdown
- Output
1. Create a react app
First, we will have a sample react application so let’s create it using create-react-app
. Run the following command to create an application.
1 | npx create-react-app cascading-dropdown-react |
Refer to the link for more information.
2. Add react-select npm package
Here, we will use the react-select npm package to integrate the dropdown. Following link will help you to integrate the dropdown.
3. Use sample JSON data
Let’s create a data.json
file to manage the JSON data and import it for further use.
data.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | [ { "region": "India", "country_code": "in", "url": "google.co.in", "languages": [ { "name": "English", "code": "en" }, { "name": "Hindi", "code": "hi" } ] }, { "region": "United Arab Emirates", "country_code": "ae", "url": "google.ae", "languages": [ { "name": "Arabic", "code": "ar" }, { "name": "English", "code": "en" } ] } ] |
We will use this data to bind the dropdowns. One is country dropdown and another is a language dropdown. The language dropdown will be populated based on the selection of the country dropdown.
4. Add logic to implement cascading dropdown
Now we will use the four different variables to manage the selected values.
- country – To manage the selection of the country dropdown.
- lang – To manage the selection of the language dropdown.
- langList – Store the list of the languages based on the selected country.
- link – Generate the link dynamically when both dropdowns are selected.
Additionally, we will create two change events to capture the dropdown selection. Also use the useEffect
to dynamically generate the link based on the country
and lang
selection.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import React, { useState, useEffect } from "react"; import Select from "react-select"; import data from './data.json'; function App() { const [country, setCountry] = useState(null); const [lang, setLang] = useState(null); const [langList, setLangList] = useState([]); const [link, setLink] = useState(""); // handle change event of the country dropdown const handleCountryChange = (obj) => { setCountry(obj); setLangList(obj.languages); setLang(null); }; // handle change event of the language dropdown const handleLanguageChange = (obj) => { setLang(obj); }; // generate the link when both dropdowns are selected useEffect(() => { if (country && lang) { setLink(`https://www.${country.url}/search?q=Clue+Mediator&gl=${country.country_code}&hl=${lang.code}`); } }, [country, lang]); return ( <div className="App"> <h3>Cascading dropdown in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3> <div style={{ width: 400, marginBottom: 20 }}> <b>Country</b> <Select placeholder="Select Country" value={country} options={data} onChange={handleCountryChange} getOptionLabel={x => x.region} getOptionValue={x => x.country_code} /> <br /> <b>Language</b> <Select placeholder="Select Language" value={lang} options={langList} onChange={handleLanguageChange} getOptionLabel={x => x.name} getOptionValue={x => x.code} /> </div> <span><b>Link:</b> {country && lang ? link : '-'}</span> </div> ); } export default App; |
5. Output
Run the project and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!!
Thanx for the awesome article
You’re welcome, Akshay!
You saved my job!!!
Thanks alot for this. But how do I get the value of the selected option saved in a functional component.
Hi Temitayo, Refer to the following article to get the selected value.
How to get selected by only value in react-select
Thanks.
I was able to use filter or find to read through the json data but where the error actually lies is that I am trying to get the country and state in functional components (react hook form) and also save it using but it can’t get the exact value to be saved
const onSubmit = data => {
console.log(“dttta”, data)
const newData = {
…data,
key: data.key,
name: data.name,
address: data.address,
country: data.country.name,
state: data.state.name
}
console.log(“NewData:”, newData)
submitForm(newData)
reset();
}
but I am getting error.
Please any help
Can you please post your error here? If possible then please replicate the issue/demo via Stackblitz or CodePen so I can easily fix it.
This helped alot. Thanks but I am having issues submitting the selected values in react hooks or in a functional component as when I console log, I can’t get the selected values.
How do I go about it. Thanks
Refer to the following article to get the selected value.
How to get selected by only value in react-select
The link to stackblitz
https://react-ujf8yq.stackblitz.io
I am actually trying to cascade dropdown for country, state and region/LGA in functional component as it won’t be lovely hard code the data but to import it. So handling the submission of the selected values gives the values undefined when console logging it.
Sorry to say but it’s hard to check your issue because your demo is not working. If you want then you can check out the GitHub source code or Stackblitz demo that given at the end of the article.
The link to stackblitz:
https://react-ujf8yq.stackblitz.io
I am actually trying to cascade drop down for Country, State and Region or LGA in react hooks and I don’t want to hard code the data but import data from data.json and also handle the submission of data selected to a table.
Thank you
awesome that’s great article
I need some help
I have a table having
id, name, dept, sec, salary
it’s in json format
in cascade dropdown i have to filter based on dept + sec and generate the data
How do I go about it
You can implement the filter for multiple object. Check the following link for more information.
Filter for multiple object in ReactJS
its nice you taught ,I want to fetch the value from mongodb Country,state,city in dependent dropdown list
You can easily fetch (Call an API to get the list) the dependent dropdown list when the first dropdown onChange event occurs.
Thanks for the article. what if I need to pre-select a country from the menu and it displays a default option?
Hi Shruthi,
You can manually perform the onChange event of the dropdown on componentDidMount.
TThanks for the brilliant tutorial. Any suggestion to remove “[Violation] Added non-passive event listener to a scroll-blocking event. Consider marking event handler as ‘passive’ to make the page more responsive. See ” in Chrome?
Great web site you have got here.. It’s hard to find high quality writing like yours these days. I really appreciate individuals like you! Take care!!