- Dynamic load country flag icons
- Able to handle not exist flag.
- Install
country-flag-icons
Package usingnpm i country-flag-icons
- Copy the following script
// country-flag.tsx import Flags3x2 from "country-flag-icons/react/3x2"; import Flags1x1 from "country-flag-icons/react/1x1"; import { hasFlag } from "country-flag-icons"; import getUnicodeFlagIcon from "country-flag-icons/unicode"; export interface CountryFlagProps extends React.HTMLAttributes<Element> { countryCode: string; flagSize?: "3x2" | "1x1"; } export const CountryFlag: React.FC<CountryFlagProps> = ({ countryCode, flagSize = "3x2", ...props }) => { countryCode = countryCode.toUpperCase(); if (!hasFlag(countryCode)) { return ( <span aria-label={countryCode} {...props}> {getUnicodeFlagIcon(countryCode)} </span> ); } const Flags = flagSize === "3x2" ? Flags3x2 : Flags1x1; const FlagComponent = Flags[countryCode as keyof typeof Flags]; return <FlagComponent aria-label={countryCode} {...props} />; };
import { CountryFlag } from "./country-flag";
const Demo = () => {
<>
<CountryFlag countryCode="uk" className="w-6 aspect-[3/2] rounded-sm" />
<CountryFlag countryCode="us" className="w-6 aspect-[3/2] rounded-sm" />
</>
}