React.js
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:
-
React
-
i18n-iso-countries (click on this to get the package link)
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 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 array
To sum up what we do above:
-
Register any languages we want to use (make sure you import them above).
-
Use the
getNames()
method attached tocountries
to get an object of all the countries and store it incountryObj
, notice"en"
, you can swap this out for the language you want to use. -
We use
Object.entries(countryObj)
to return an array ofcountryObj
own enumerable key-value pairs. -
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 selectedCountry
We can now render our country-select component, we are using Material-UI for this section.
Render the countries
To sum up what we do here:
-
Pass the currently selected country and the onChange handler to
Select
-
Next as the children of the parent
Select
, we are going to map out our country array and render each one as aMenuItem
, make sure to pass the key prop as something unique for each item.
Full code
Working 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.