Skip to content

Dynamic Flags

  • You can enumerate the possible codes (finite set): use Named Imports + Map (recommended)
  • You need to render any code synchronously and stay offline: use DynamicFlag

In many apps, country codes come from runtime data:

  • User-selected countries (forms, settings)
  • API/database values (profiles, records)
  • Location-based content
Section titled “Strategy 1: Named Imports + Map (Recommended)”

This stays offline-first while still letting you render runtime values.

import { FlagCn, FlagGb, FlagUs } from '@sankyu/react-circle-flags'
const FLAGS = {
cn: FlagCn,
gb: FlagGb,
us: FlagUs,
} as const
export function CountryFlag({ code }: { code: string }) {
const normalized = code.toLowerCase()
const Flag = FLAGS[normalized as keyof typeof FLAGS]
if (!Flag) return <span title="Unknown country code">{code.toUpperCase()}</span>
return <Flag width={36} height={36} />
}

Strategy 2: DynamicFlag (Offline, Bundles All Flags)

Section titled “Strategy 2: DynamicFlag (Offline, Bundles All Flags)”

Use this when you truly need to support any runtime code and still render synchronously with full SVG props.

import { DynamicFlag } from '@sankyu/react-circle-flags'
export function CountryFlag({ code }: { code: string }) {
return <DynamicFlag code={code} width={36} height={36} />
}

If you can guarantee that your runtime value is already a valid country code (for example, from a typed list), enable strict for stronger TypeScript constraints:

import { DynamicFlag, coerceFlagCode } from '@sankyu/react-circle-flags'
export function CountryFlag({ codeFromApi }: { codeFromApi: string }) {
// Coerce unknown runtime data to a safe union (unknown values become "xx")
const safeCode = coerceFlagCode(codeFromApi)
return <DynamicFlag strict code={safeCode} width={36} height={36} />
}
StrategyBundle impactNetworkOffline-first
Named Imports + Map~950 bytes per imported flagNone
DynamicFlag~600 KBNone