Shadcn Country / Region Select
An implementation of a Country / Region Select component built on top of Shadcn UI's input component.
Setup
Install Shadcn via CLI
Run the shadcn-ui
init command to setup your project:
npx shadcn-ui@latest init
Install necessary Shadcn components:
Run the shadcn-ui
add command to add the necessary shadcn components to your project:
npx shadcn-ui@latest add select
Install necessary Country Region Data package:
npm install country-region-data
To use the country/region select component:
Snippets
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { filterCountries } from "@/lib/helpers";
//@ts-ignore
import countryRegionData from "country-region-data/dist/data-umd";
import { useEffect, useState } from "react";
export interface Region {
name: string;
shortCode: string;
}
export interface CountryRegion {
countryName: string;
countryShortCode: string;
regions: Region[];
}
interface CountrySelectProps {
priorityOptions?: string[];
whitelist?: string[];
blacklist?: string[];
onChange?: (value: string) => void;
className?: string;
placeholder?: string;
}
function CountrySelect({
priorityOptions = [],
whitelist = [],
blacklist = [],
onChange = () => {},
className,
placeholder = "Country",
}: CountrySelectProps) {
const [countries, setCountries] = useState<CountryRegion[]>([]);
useEffect(() => {
setCountries(
filterCountries(countryRegionData, priorityOptions, whitelist, blacklist),
);
}, []);
return (
<Select
onValueChange={(value: string) => {
onChange(value);
}}
>
<SelectTrigger className={className}>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
{countries.map(({ countryName, countryShortCode }) => (
<SelectItem key={countryShortCode} value={countryShortCode}>
{countryName}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
export default CountrySelect;
Properties
With country / region
This properties are valid with the two component country and region.
whiteList
Specify which countries should appear. This just shows the United States and China.
blackList
Specify which countries should NOT appear. This will omit Afhganistan, Aland Islands and Albania.
priorityOptions
Make Canada, United States and the Brazil appear first in the dropdown list.