통화 이름 및 기호 표시

현지화된 방식으로 통화 정보 표시하기

문제

애플리케이션에서 'USD'와 같은 통화를 참조해야 합니다. 단순히 이 코드를 표시하는 것은 암호 같습니다. 전체 이름인 'US Dollar'를 표시하는 것이 더 낫지만, 이 이름 자체도 번역이 필요합니다('dólar estadounidense', 'Dollar américain'). 또한 올바른 기호($, US$, CA$)는 맥락 없이는 모호할 수 있습니다.

해결 방법

react-intlFormattedNumber 컴포넌트를 currencyDisplay 옵션과 함께 사용하세요. 이를 통해 통화를 기호(기본값), 전체 현지화된 이름 또는 ISO 코드로 표시할 수 있으며, 모두 현재 로케일에 맞게 올바르게 형식화됩니다.

단계

1. 통화 표시를 위한 클라이언트 컴포넌트 생성

FormattedNumber 컴포넌트는 클라이언트 컴포넌트 내부에서 사용해야 합니다. currencyDisplay 옵션을 prop으로 받는 app/components/LocalizedCurrency.tsx 파일을 생성하여 재사용 가능하게 만드세요.

// app/components/LocalizedCurrency.tsx
'use client';

import { FormattedNumber } from 'react-intl';

type Props = {
  value: number;
  currency: string;
  displayAs: 'symbol' | 'name' | 'code';
};

export default function LocalizedCurrency({
  value,
  currency,
  displayAs,
}: Props) {
  return (
    <FormattedNumber
      value={value}
      style="currency"
      currency={currency}
      currencyDisplay={displayAs}
    />
  );
}

이제 이 컴포넌트는 currencyDisplay 옵션을 직접 제어하는 displayAs prop을 받습니다.

2. 페이지에서 컴포넌트 사용

이제 이 컴포넌트를 페이지에서 사용하여 displayAs prop을 변경함으로써 다양한 통화 형식을 표시할 수 있습니다.

// app/[lang]/page.tsx
import LocalizedCurrency from '@/app/components/LocalizedCurrency';

export default function Home() {
  const price = 1250.75;
  const currency = 'USD';

  return (
    <div>
      <h1>Currency Display Options</h1>
      <p>
        Default (symbol):
        <LocalizedCurrency
          value={price}
          currency={currency}
          displayAs="symbol"
        />
      </p>
      <p>
        Full name (name):
        <LocalizedCurrency
          value={price}
          currency={currency}
          displayAs="name"
        />
      </p>
      <p>
        ISO code (code):
        <LocalizedCurrency
          value={price}
          currency={currency}
          displayAs="code"
        />
      </p>
    </div>
  );
}

/en를 방문하면 'name' 옵션에 대해 "1,250.75 US dollars"가 표시됩니다. /es를 방문하면 동일한 줄이 "1.250,75 dólares estadounidenses"로 렌더링되어 통화 이름 자체가 번역되고 올바르게 형식화되었음을 보여줍니다.