Skip to content

Instantly share code, notes, and snippets.

@soranoo
Last active April 23, 2024 23:23
Show Gist options
  • Select an option

  • Save soranoo/10eb64108b099b38e1e78f42a822ecaf to your computer and use it in GitHub Desktop.

Select an option

Save soranoo/10eb64108b099b38e1e78f42a822ecaf to your computer and use it in GitHub Desktop.

Revisions

  1. soranoo renamed this gist Apr 23, 2024. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. soranoo created this gist Apr 23, 2024.
    55 changes: 55 additions & 0 deletions index.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    ### 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
    ```ts
    // 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

    ```ts
    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](https://gist.github.com/assets/46896789/4baaa584-a4ef-4042-ad4a-8a2d1ebf05b6)