Skip to content

Instantly share code, notes, and snippets.

@soranoo
Last active April 23, 2024 23:23
Show Gist options
  • Save soranoo/10eb64108b099b38e1e78f42a822ecaf to your computer and use it in GitHub Desktop.
Save soranoo/10eb64108b099b38e1e78f42a822ecaf to your computer and use it in GitHub Desktop.
React Dynamic Country Flag Icons

Features

  1. Dynamic load country flag icons
  2. Able to handle not exist flag.

Installation

  1. Install country-flag-icons Package using npm i country-flag-icons
  2. 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} />;
    };

Example

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" />
  </>
}

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment