Create a Country Select Component with React

How to create a country select dropdown in React using Material-UI and i18n-iso-countries.

image

In this tutorial, we will learn how to create a simple select/dropdown for all countries as inputting one by one is very time-consuming. For this reason, we will be using an external library/package to get data for all countries.

We will be using:

We are using this particular package as it comes with some other features that can be useful if your app uses multiple languages, or you have already implemented something like i18next in your app.

Note: You can use any UI library, I'm just using Material-UI for simplicity.

First up, get your react-app started, and install all necessary dependencies.

Make sure you have the following dependencies imported into your app:

Import required librariesImport required libraries

Next up let's get our country data and sort it. The data returned from the library is not an array, but instead an object of key-value pairs, eg: { MY: “Malaysia” }. So we need to sort it before we can use it.

Convert countries objects into an arrayConvert countries objects into an array

To sum up what we do above:

  1. Register any languages we want to use (make sure you import them above).

  2. Use the getNames() method attached to countries to get an object of all the countries and store it in countryObj, notice "en" , you can swap this out for the language you want to use.

  3. We use Object.entries(countryObj) to return an array of countryObj own enumerable key-value pairs.

  4. Lastly, map these key-value pairs into an array of objects containing a label & value.

Now we can use our new array of countries in a Select component! We are going to use the useState hook to manage the Select's state and also create a function to handle the onChange event.

Handler function & useState for selectedCountryHandler function & useState for selectedCountry

We can now render our country-select component, we are using Material-UI for this section.

Render the countriesRender the countries

To sum up what we do here:

  1. Pass the currently selected country and the onChange handler to Select

  2. Next as the children of the parent Select, we are going to map out our country array and render each one as a MenuItem, make sure to pass the key prop as something unique for each item.

Full codeFull code

Working demoWorking demo

That's all you need to implement a language-based country-select in React

You can expand on this to make it more dynamic by adding a language switcher, and switch the language the countries is in by replacing the "en" in the getNames() method with a dynamic value.

Link to code sandbox here.

Thanks for staying till the end, I hope it helped you.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics