Skip to main content

Currency Converter

A minimal shadcn-style currency converter card with animated NumberFlow amounts, USD/EUR/GBP/JPY pickers, a spring-rotating swap action, a live exchange-rate badge, and a built-in dark mode toggle.

CardReactTailwind CSSMotionRadix UINumber Flow
CSSTailwind

Manual

Create a file and paste the following code into it.

src/components/ui/currency-converter.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
"use client";

import {
  createContext,
  useContext,
  useEffect,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { motion, useReducedMotion } from "motion/react";
import NumberFlow from "@number-flow/react";
import * as Select from "@radix-ui/react-select";
import {
  ArrowsDownUp,
  CaretDown,
  Check,
  Moon,
  Sun,
} from "@phosphor-icons/react";
import { cn } from "@/lib/cn";

/* ─── Currency model & conversion ────────────── */

export type Currency = {
  /** ISO-style code shown in the picker, e.g. "USD". */
  code: string;
  /** Full display name, e.g. "United States Dollar". */
  label: string;
  /** Symbol rendered next to the amount, e.g. "$". */
  symbol: string;
  /** Units of this currency per 1 USD (the base). USD itself is 1. */
  perUsd: number;
  /** Fraction digits shown for this currency. Defaults to 2. */
  decimals?: number;
};

type CurrencyMap = Record<string, Currency>;

const DEFAULT_CURRENCIES: Currency[] = [
  { code: "USD", label: "United States Dollar", symbol: "$", perUsd: 1 },
  { code: "EUR", label: "Euro", symbol: "€", perUsd: 0.92 },
  { code: "GBP", label: "British Pound", symbol: "£", perUsd: 0.78 },
  { code: "JPY", label: "Japanese Yen", symbol: "¥", perUsd: 157.43, decimals: 0 },
];

function buildMap(currencies: Currency[]): CurrencyMap {
  return Object.fromEntries(currencies.map((c) => [c.code, c]));
}

function decimalsFor(currency: Currency | undefined): number {
  const decimals = currency?.decimals;
  if (decimals === undefined) return 2;
  // Intl/NumberFlow only accept an integer in [0, 20]; fall back to 2 otherwise.
  return Number.isInteger(decimals) && decimals >= 0 && decimals <= 20
    ? decimals
    : 2;
}

/** Convert an amount between two codes. Returns 0 for unknown codes, non-finite input, or non-positive rates. */
function convert(amount: number, from: string, to: string, map: CurrencyMap): number {
  const source = map[from];
  const target = map[to];
  if (!source || !target || !Number.isFinite(amount)) return 0;
  if (!(source.perUsd > 0) || !(target.perUsd > 0)) return 0;
  if (!Number.isFinite(source.perUsd) || !Number.isFinite(target.perUsd)) return 0;
  return (amount / source.perUsd) * target.perUsd;
}

function formatRate(from: string, to: string, map: CurrencyMap): string {
  return convert(1, from, to, map).toLocaleString("en-US", {
    minimumFractionDigits: 4,
    maximumFractionDigits: 4,
  });
}

/** Parse a free-typed string into a non-negative number (NaN/negative → 0). */
function parseAmount(raw: string): number {
  const parsed = Number.parseFloat(raw);
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
}

/** Keep only digits and a single decimal point while the user types. Negative input (leading `-` or accounting `(`) is rejected — a send amount is never negative. */
function sanitizeAmount(raw: string): string {
  if (/^\s*[-(]/.test(raw)) return "";
  const cleaned = raw.replace(/[^\d.]/g, "");
  const dot = cleaned.indexOf(".");
  if (dot === -1) return cleaned;
  return cleaned.slice(0, dot + 1) + cleaned.slice(dot + 1).replace(/\./g, "");
}

/* ─── Motion springs & easings ───────────────── */

const VALUE_SPRING = { type: "spring", stiffness: 500, damping: 22, mass: 0.6 } as const;
const RATE_SPRING = { type: "spring", stiffness: 620, damping: 38, mass: 0.8 } as const;
const SWAP_SPRING = { type: "spring", stiffness: 320, damping: 24, mass: 1 } as const;

const NUMBER_EASING =
  "linear(0, 0.0018, 0.0069 1.15%, 0.026 2.3%, 0.0637, 0.1135 5.18%, 0.2229 7.78%, 0.5977 15.84%, 0.7014, 0.7904, 0.8641, 0.9228, 0.9676 28.8%, 1.0032 31.68%, 1.0225, 1.0352 36.29%, 1.0431 38.88%, 1.046 42.05%, 1.0448 44.35%, 1.0407 47.23%, 1.0118 61.63%, 1.0025 69.41%, 0.9981 80.35%, 0.9992 99.94%)";

/* ─── Self-contained shadcn token scope ──────── */
// shadcn token utilities are emitted as literal values under Tailwind's
// `@theme inline`, so runtime variable overrides only reach *arbitrary* values
// (`bg-[var(--color-…)]`). The signature feature here is a light/dark toggle, so
// the component ships its own scoped oklch tokens for both modes. `data-cc-scope`
// is also set on the Radix Select portal content (rendered outside the root) so
// the popover inherits the same tokens.

const SCOPED_TOKENS = `
@import url('https://fonts.googleapis.com/css2?family=Urbanist:wght@400;500;600;700;800;900&display=swap');
[data-cc-scope]{
font-family:'Urbanist',ui-sans-serif,system-ui,sans-serif;
--color-background:oklch(100% 0 0);--color-foreground:oklch(14.5% 0 0);
--color-card:oklch(100% 0 0);--color-card-foreground:oklch(14.5% 0 0);
--color-popover:oklch(100% 0 0);--color-popover-foreground:oklch(14.5% 0 0);
--color-primary:oklch(20.5% 0 0);--color-primary-foreground:oklch(98.5% 0 0);
--color-secondary:oklch(97% 0 0);--color-secondary-foreground:oklch(20.5% 0 0);
--color-muted:oklch(97% 0 0);--color-muted-foreground:oklch(55.6% 0 0);
--color-accent:oklch(97% 0 0);--color-accent-foreground:oklch(20.5% 0 0);
--color-border:oklch(92.2% 0 0);--color-input:oklch(92.2% 0 0);--color-ring:oklch(70.8% 0 0);
}
[data-cc-scope].dark{
--color-background:oklch(14.5% 0 0);--color-foreground:oklch(98.5% 0 0);
--color-card:oklch(20.5% 0 0);--color-card-foreground:oklch(98.5% 0 0);
--color-popover:oklch(20.5% 0 0);--color-popover-foreground:oklch(98.5% 0 0);
--color-primary:oklch(92.2% 0 0);--color-primary-foreground:oklch(20.5% 0 0);
--color-secondary:oklch(26.9% 0 0);--color-secondary-foreground:oklch(98.5% 0 0);
--color-muted:oklch(26.9% 0 0);--color-muted-foreground:oklch(70.8% 0 0);
--color-accent:oklch(26.9% 0 0);--color-accent-foreground:oklch(98.5% 0 0);
--color-border:oklch(100% 0 0 / 0.1);--color-input:oklch(100% 0 0 / 0.15);--color-ring:oklch(55.6% 0 0);
}
@keyframes cc-card-enter{from{opacity:0;transform:translateY(14px) scale(0.98)}to{opacity:1;transform:none}}
[data-cc-scope] .cc-card-enter{animation:cc-card-enter .5s cubic-bezier(.22,1,.36,1) both}
@media (prefers-reduced-motion:reduce){[data-cc-scope] .cc-card-enter{animation:none}}
`;

/* ─── Shared context ─────────────────────────── */

type ConverterContextValue = {
  isDark: boolean;
  currencies: Currency[];
  map: CurrencyMap;
};

const ConverterContext = createContext<ConverterContextValue>({
  isDark: false,
  currencies: DEFAULT_CURRENCIES,
  map: buildMap(DEFAULT_CURRENCIES),
});

/** Two-pass mount guard — renders a static fallback on the server, animates after hydration. */
function useMounted(): boolean {
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  return mounted;
}

/* ─── Pure-CSS mini flag glyphs ───────────────── */

function FlagIcon({ currency }: { currency: Currency | undefined }) {
  const code = currency?.code;
  const isKnown = code === "USD" || code === "EUR" || code === "GBP" || code === "JPY";
  return (
    <span
      aria-hidden="true"
      className={cn(
        "relative grid size-7 shrink-0 place-items-center overflow-hidden rounded-full border border-[var(--color-border)]",
        code === "EUR" && "bg-blue-800",
        code === "GBP" && "bg-blue-950",
        code === "JPY" && "bg-[var(--color-card)]",
        !isKnown && "bg-[var(--color-muted)]",
      )}
    >
      {code === "USD" && (
        <>
          <span className="absolute inset-0 grid grid-rows-6">
            <span className="bg-red-700" />
            <span className="bg-[var(--color-card)]" />
            <span className="bg-red-700" />
            <span className="bg-[var(--color-card)]" />
            <span className="bg-red-700" />
            <span className="bg-[var(--color-card)]" />
          </span>
          <span className="absolute left-0 top-0 size-3 rounded-br-sm bg-blue-900" />
        </>
      )}
      {code === "EUR" && (
        <span className="m-auto size-3 rounded-full bg-amber-400 shadow-sm" />
      )}
      {code === "GBP" && (
        <>
          <span className="absolute inset-x-0 top-1/2 h-1 -translate-y-1/2 bg-[var(--color-card)]" />
          <span className="absolute inset-y-0 left-1/2 w-1 -translate-x-1/2 bg-[var(--color-card)]" />
          <span className="absolute inset-x-0 top-1/2 h-px -translate-y-1/2 bg-red-700" />
          <span className="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-red-700" />
        </>
      )}
      {code === "JPY" && (
        <span className="m-auto size-3 rounded-full bg-red-600" />
      )}
      {!isKnown && (
        <span className="text-xs font-bold text-[var(--color-muted-foreground)]">
          {currency?.symbol ?? "?"}
        </span>
      )}
    </span>
  );
}

/* ─── Animated currency symbol ────────────────── */

// A new `key` remounts the span, replaying its enter spring on currency change.
// `initial={false}` until mounted suppresses the animation on first paint (and
// keeps SSR/client markup identical), matching the original's no-flash entrance.
function CurrencySymbol({ currency }: { currency: Currency | undefined }) {
  const reduced = useReducedMotion();
  const mounted = useMounted();
  const symbol = currency?.symbol ?? "";

  return (
    <motion.span
      key={currency?.code ?? symbol}
      aria-hidden="true"
      className="text-4xl font-bold text-[var(--color-muted-foreground)]/60"
      initial={!mounted || reduced ? false : { opacity: 0, scale: 0.75, y: 5 }}
      animate={{ opacity: 1, scale: 1, y: 0 }}
      transition={reduced ? { duration: 0 } : VALUE_SPRING}
    >
      {symbol}
    </motion.span>
  );
}

/* ─── Read-only animated amount (NumberFlow) ──── */

function AmountDisplay({ value, currency }: { value: number; currency: Currency | undefined }) {
  const mounted = useMounted();
  const decimals = decimalsFor(currency);
  const formatted = value.toLocaleString("en-US", {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  });

  return (
    <div className="flex items-baseline justify-end gap-1 tabular-nums">
      <CurrencySymbol currency={currency} />
      {mounted ? (
        <NumberFlow
          value={value}
          format={{
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals,
          }}
          transformTiming={{ duration: 750, easing: NUMBER_EASING }}
          spinTiming={{ duration: 750, easing: NUMBER_EASING }}
          opacityTiming={{ duration: 350, easing: "ease-out" }}
          aria-label={`${formatted} ${currency?.code ?? ""}`}
          className="text-4xl font-bold leading-none tracking-tight text-[var(--color-foreground)]"
        />
      ) : (
        <span className="text-4xl font-bold leading-none tracking-tight text-[var(--color-foreground)]">
          {formatted}
        </span>
      )}
    </div>
  );
}

/* ─── Editable amount field ───────────────────── */

function AmountInput({
  value,
  currency,
  onChange,
  onCommit,
}: {
  value: string;
  currency: Currency | undefined;
  onChange: (next: string) => void;
  onCommit: () => void;
}) {
  return (
    <div className="flex items-baseline justify-end gap-1 tabular-nums">
      <CurrencySymbol currency={currency} />
      {/* An invisible ghost (in normal flow) sizes the field to its content AND
          gives the wrapper a text baseline, so the symbol stays flush against the
          number — matching the read-only "They get" row. The input is overlaid
          absolutely; `maxLength` keeps a long paste from blowing out the row. */}
      <span className="relative inline-block max-w-full">
        <span
          aria-hidden="true"
          className="invisible block whitespace-pre text-4xl font-bold leading-none tracking-tight tabular-nums"
        >
          {value || "0"}
        </span>
        <input
          inputMode="decimal"
          maxLength={12}
          value={value}
          onChange={(event) => onChange(sanitizeAmount(event.target.value))}
          onBlur={onCommit}
          onKeyDown={(event) => {
            if (event.key === "Enter") event.currentTarget.blur();
          }}
          aria-label={`Amount to send in ${currency?.label ?? currency?.code ?? "selected currency"}`}
          className="absolute inset-0 w-full border-0 bg-transparent p-0 text-right text-4xl font-bold leading-none tracking-tight text-[var(--color-foreground)] caret-[var(--color-primary)] tabular-nums outline-none"
        />
      </span>
    </div>
  );
}

/* ─── Currency picker (Radix Select) ──────────── */

function CurrencySelect({
  value,
  onValueChange,
}: {
  value: string;
  onValueChange: (next: string) => void;
}) {
  const reduced = useReducedMotion();
  const { isDark, currencies, map } = useContext(ConverterContext);
  const mounted = useMounted();
  const selected = map[value];

  return (
    <Select.Root value={value} onValueChange={onValueChange}>
      <Select.Trigger
        aria-label={`Select currency, currently ${selected?.label ?? value}`}
        className="group inline-flex h-11 min-w-[7.5rem] shrink-0 items-center gap-1.5 rounded-full border border-[var(--color-border)] bg-[var(--color-card)] px-2 text-left outline-none transition-[border-color,box-shadow] duration-150 hover:border-[var(--color-muted-foreground)]/40 focus-visible:ring-2 focus-visible:ring-[var(--color-ring)] data-[state=open]:border-[var(--color-ring)]"
      >
        <span className="inline-flex min-w-0 flex-1 items-center overflow-hidden">
          <motion.span
            key={value}
            className="inline-flex items-center gap-2"
            initial={!mounted || reduced ? false : { opacity: 0, scale: 0.72, y: 7 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            transition={reduced ? { duration: 0 } : VALUE_SPRING}
          >
            <FlagIcon currency={selected} />
            <span className="text-base font-black tracking-normal text-[var(--color-foreground)]">
              {value}
            </span>
          </motion.span>
        </span>
        <Select.Icon asChild>
          <CaretDown className="size-4 shrink-0 text-[var(--color-muted-foreground)] transition-transform duration-200 group-data-[state=open]:rotate-180" />
        </Select.Icon>
      </Select.Trigger>
      <Select.Portal>
        <Select.Content
          position="popper"
          sideOffset={8}
          data-cc-scope
          className={cn(
            "z-50 min-w-56 overflow-hidden rounded-2xl border border-[var(--color-border)] bg-[var(--color-popover)] p-1.5 text-[var(--color-popover-foreground)]",
            isDark && "dark",
          )}
        >
          <Select.Viewport>
            {currencies.map((currency) => (
              <Select.Item
                key={currency.code}
                value={currency.code}
                className="relative flex cursor-default select-none items-center gap-3 rounded-xl px-3 py-2.5 outline-none transition-colors data-[highlighted]:bg-[var(--color-accent)]"
              >
                <FlagIcon currency={currency} />
                <Select.ItemText>
                  <span className="grid gap-0.5">
                    <span className="text-sm font-bold leading-none text-[var(--color-foreground)]">
                      {currency.code}
                    </span>
                    <span className="text-xs leading-none text-[var(--color-muted-foreground)]">
                      {currency.label}
                    </span>
                  </span>
                </Select.ItemText>
                <Select.ItemIndicator className="ml-auto text-[var(--color-primary)]">
                  <Check className="size-3.5" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Viewport>
        </Select.Content>
      </Select.Portal>
    </Select.Root>
  );
}

/* ─── Single send/receive row ─────────────────── */

function CurrencyRow({
  label,
  currency,
  onCurrencyChange,
  children,
}: {
  label: string;
  currency: string;
  onCurrencyChange: (next: string) => void;
  children: ReactNode;
}) {
  return (
    <div className="relative overflow-hidden rounded-xl border border-[var(--color-border)] bg-[var(--color-muted)] px-5 py-4">
      <div className="flex min-h-[4.5rem] flex-row items-center justify-between gap-4">
        <CurrencySelect value={currency} onValueChange={onCurrencyChange} />
        <div className="grid min-w-0 flex-1 justify-items-end gap-1">
          <span className="text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--color-muted-foreground)]/60">
            {label}
          </span>
          {children}
        </div>
      </div>
    </div>
  );
}

/* ─── Main converter ──────────────────────────── */

export type CurrencyConverterProps = {
  /** Currencies offered in both pickers. Defaults to USD/EUR/GBP/JPY. */
  currencies?: Currency[];
  /** Initial "You send" currency code. Falls back to the first currency. */
  defaultFrom?: string;
  /** Initial "They get" currency code. Falls back to a currency other than `from`. */
  defaultTo?: string;
  /** Initial amount to send. Defaults to 6.39. */
  defaultAmount?: number;
  /** Fires whenever the amount or either currency changes. */
  onConvert?: (result: {
    amount: number;
    from: string;
    to: string;
    converted: number;
  }) => void;
  /** Primary action button label. Defaults to "Connect Wallet". */
  ctaLabel?: string;
  /** Primary action button click handler. */
  onCtaClick?: () => void;
  /** Start in dark mode. Defaults to false. */
  defaultDark?: boolean;
  /** Extra classes merged onto the themed outer surface. */
  className?: string;
};

/**
 * Currency Converter — a self-contained shadcn-style card with an editable
 * "You send" amount, animated NumberFlow "They get" output, Radix Select
 * currency pickers, a spring-rotating swap action, a live exchange-rate badge,
 * and a built-in light/dark toggle. Renders as a card anywhere; fills its
 * container's height when one is provided.
 *
 * @param {Currency[]} currencies - Pickable currencies [Optional, default: USD/EUR/GBP/JPY]
 * @param {string} defaultFrom - Initial send currency code [Optional, default: first currency]
 * @param {string} defaultTo - Initial receive currency code [Optional, default: second currency]
 * @param {number} defaultAmount - Initial send amount [Optional, default: 6.39]
 * @param {Function} onConvert - Called with {amount, from, to, converted} on change [Optional]
 * @param {string} ctaLabel - Primary button text [Optional, default: "Connect Wallet"]
 * @param {Function} onCtaClick - Primary button handler [Optional]
 * @param {boolean} defaultDark - Start dark [Optional, default: false]
 * @param {string} className - Extra classes on the outer surface [Optional]
 *
 * @example
 * <CurrencyConverter
 *   defaultFrom="EUR"
 *   defaultTo="USD"
 *   defaultAmount={100}
 *   onConvert={({ converted }) => console.log(converted)}
 *   ctaLabel="Send money"
 *   onCtaClick={openCheckout}
 * />
 */
export default function CurrencyConverter({
  currencies = DEFAULT_CURRENCIES,
  defaultFrom,
  defaultTo,
  defaultAmount = 6.39,
  onConvert,
  ctaLabel = "Connect Wallet",
  onCtaClick,
  defaultDark = false,
  className,
}: CurrencyConverterProps = {}) {
  const reduced = useReducedMotion();
  const mounted = useMounted();
  const map = buildMap(currencies);

  // Resolve initial codes against the provided list; never let from === to.
  const initialFrom = map[defaultFrom ?? ""] ? defaultFrom! : currencies[0]?.code ?? "";
  const fallbackTo =
    currencies.find((c) => c.code !== initialFrom)?.code ?? initialFrom;
  const requestedTo = map[defaultTo ?? ""] ? defaultTo! : fallbackTo;
  const initialTo = requestedTo === initialFrom ? fallbackTo : requestedTo;
  const initialAmount = Math.max(0, defaultAmount);

  const [from, setFrom] = useState(initialFrom);
  const [to, setTo] = useState(initialTo);
  const [amount, setAmount] = useState(initialAmount);
  const [draft, setDraft] = useState(() => String(initialAmount));
  const [isDark, setIsDark] = useState(defaultDark);
  const [rotation, setRotation] = useState(0);

  const converted = convert(amount, from, to, map);
  const rate = formatRate(from, to, map);

  // Hold the latest `onConvert` in a ref so the emit effect can depend only on
  // the conversion inputs. Depending on `onConvert` itself would re-fire (and,
  // with an inline `onConvert={(r) => setState(r)}`, infinitely loop) on every
  // parent render purely because the callback identity changed.
  const onConvertRef = useRef(onConvert);
  useEffect(() => {
    onConvertRef.current = onConvert;
  });
  useEffect(() => {
    onConvertRef.current?.({ amount, from, to, converted });
  }, [amount, from, to, converted]);

  // Reconcile selections if the `currencies` prop later changes to exclude them
  // (e.g. async loading or a swapped-in list), so we never display or emit a
  // rate for a code that is no longer offered.
  useEffect(() => {
    const codes = currencies.map((c) => c.code);
    if (codes.length === 0) return;
    setFrom((prev) => (codes.includes(prev) ? prev : codes[0]));
    setTo((prev) =>
      codes.includes(prev) ? prev : codes[codes.length > 1 ? 1 : 0],
    );
  }, [currencies]);

  function handleFromChange(next: string) {
    if (next === from) return;
    if (next === to) setTo(from);
    setFrom(next);
  }

  function handleToChange(next: string) {
    if (next === to) return;
    if (next === from) setFrom(to);
    setTo(next);
  }

  function commitAmount() {
    const parsed = parseAmount(draft);
    setAmount(parsed);
    setDraft(String(parsed));
  }

  function handleSwap() {
    if (!reduced) setRotation((r) => r + 180);
    // The converted value becomes the new send amount; round it to the new
    // source currency's precision (e.g. 0 decimals for JPY) and preserve zero.
    const factor = 10 ** decimalsFor(map[to]);
    const nextAmount = Math.round(converted * factor) / factor;
    setFrom(to);
    setTo(from);
    setAmount(nextAmount);
    setDraft(String(nextAmount));
  }

  return (
    <ConverterContext.Provider value={{ isDark, currencies, map }}>
      <style>{SCOPED_TOKENS}</style>
      <div
        data-cc-scope
        className={cn(
          "flex min-h-full w-full items-center justify-center bg-[var(--color-background)] px-4 py-6 text-[var(--color-foreground)] transition-colors duration-300 sm:px-6",
          isDark && "dark",
          className,
        )}
      >
        {/* CSS-driven entrance (not Motion): a mount animation whose props
            depend on the async `useReducedMotion` value freezes mid-flight, and
            CSS honors `prefers-reduced-motion` natively via the scoped <style>. */}
        <div className="cc-card-enter w-full max-w-[34rem]">
          <div className="rounded-[26px] border border-[var(--color-border)] bg-[var(--color-secondary)] p-5 shadow-lg backdrop-blur-2xl transition-colors duration-300">
            <header className="mb-5 flex flex-row items-center justify-between gap-3 px-3">
              <div className="flex flex-wrap items-center gap-2.5">
                <h2 className="text-xl font-bold leading-none tracking-tight text-[var(--color-foreground)]">
                  Convert
                </h2>
                <div className="overflow-hidden rounded-full bg-[var(--color-background)] px-3 py-1.5 shadow-sm">
                  <motion.span
                    key={`${from}-${to}`}
                    className="block whitespace-nowrap text-xs font-semibold text-[var(--color-muted-foreground)]"
                    initial={!mounted || reduced ? false : { opacity: 0, y: 8, scale: 0.88 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    transition={reduced ? { duration: 0 } : RATE_SPRING}
                  >
                    1 {from} = {rate} {to}
                  </motion.span>
                </div>
              </div>
              <button
                type="button"
                aria-label={`Switch to ${isDark ? "light" : "dark"} theme`}
                aria-pressed={isDark}
                onClick={() => setIsDark((d) => !d)}
                className="hidden w-fit items-center gap-1.5 rounded-full px-2.5 py-1.5 text-sm font-semibold text-[var(--color-muted-foreground)] transition-colors duration-150 hover:bg-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-ring)] md:flex"
              >
                {isDark ? (
                  <Sun className="size-3.5" aria-hidden="true" />
                ) : (
                  <Moon className="size-3.5" aria-hidden="true" />
                )}
                <span>{isDark ? "Light" : "Dark"}</span>
              </button>
            </header>

            <div className="rounded-3xl bg-[var(--color-card)] p-4">
              <div className="relative grid gap-3">
                <CurrencyRow
                  label="You send"
                  currency={from}
                  onCurrencyChange={handleFromChange}
                >
                  <AmountInput
                    value={draft}
                    currency={map[from]}
                    onChange={setDraft}
                    onCommit={commitAmount}
                  />
                </CurrencyRow>
                <motion.button
                  type="button"
                  aria-label="Swap currencies"
                  animate={{ rotate: rotation }}
                  transition={SWAP_SPRING}
                  whileTap={{ scale: 0.94 }}
                  onClick={handleSwap}
                  className="absolute left-1/2 top-1/2 z-10 grid size-10 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border border-[var(--color-border)] bg-[var(--color-card)] text-[var(--color-muted-foreground)] transition-colors duration-150 hover:bg-[var(--color-accent)] hover:text-[var(--color-foreground)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-ring)]"
                >
                  <ArrowsDownUp className="size-3.5" weight="bold" />
                </motion.button>
                <CurrencyRow
                  label="They get"
                  currency={to}
                  onCurrencyChange={handleToChange}
                >
                  <AmountDisplay value={converted} currency={map[to]} />
                </CurrencyRow>
              </div>

              <div className="mt-4 border-t border-dashed border-[var(--color-border)] pt-3.5">
                <div className="flex flex-row items-center justify-between gap-2">
                  <span className="text-sm font-semibold text-[var(--color-muted-foreground)]">
                    Fee
                  </span>
                  <span className="text-sm font-semibold">
                    <span className="text-[var(--color-foreground)]">$0.00</span>
                    <span className="px-1.5 text-[var(--color-muted-foreground)]/60">·</span>
                    <span className="text-[var(--color-muted-foreground)]">No hidden fees</span>
                  </span>
                </div>
              </div>
            </div>

            <div className="mt-4">
              <button
                type="button"
                onClick={onCtaClick}
                className="inline-flex h-12 w-full shrink-0 items-center justify-center rounded-full border border-transparent bg-[var(--color-primary)] text-sm font-medium text-[var(--color-primary-foreground)] whitespace-nowrap transition-all outline-none select-none hover:bg-[var(--color-primary)]/80 focus-visible:border-[var(--color-ring)] focus-visible:ring-[3px] focus-visible:ring-[var(--color-ring)]/50 active:translate-y-px disabled:pointer-events-none disabled:opacity-50"
              >
                {ctaLabel}
              </button>
            </div>
          </div>
        </div>
      </div>
    </ConverterContext.Provider>
  );
}

Update the import paths to match your project setup.

Similar components

Agent Usage Metrics

Team Cards with Gradient Hover

Max

Dashboard Chart

Pricing Table

Resource details

PublishedJune 8, 2026
CategoryCard
ReactTailwind CSSMotionRadix UINumber Flow