.format is not a function on Intl.NumberFormat React JS

203 views Asked by At

I'm trying to convert a number to a currency using the below function:

let currencyFormatter = new Intl.NumberFormat("en-GB", {
  style: "currency",
  currency: "GBP",
  minimumFractionDigits: 2,
});

However, I am getting the above error .format is not a function.

I am using the function as such;

<tbody>
    {data.items.map((item) => (
        <tr key={item} className="text-right">
            <td className="text-left py-4 align-top text-sm">{item.description}</td>
            <td className="py-4 min-w-[100px] align-top text-sm font-bold">{currencyFormatter.format(item.price)} // ERROR HERE!</td>
            <td className="py-4 min-w-[100px] align-top text-sm">{item.quantity}</td>
            <td className="py-4 min-w-[100px] align-top text-sm font-bold">{item.price * item.quantity}</td>
        </tr>
    ))}
</tbody>

Inc. Import/Export

currency.js

export let currencyFormatter = new Intl.NumberFormat("en-GB", {
  style: "currency",
  currency: "GBP",
  minimumFractionDigits: 2,
});

page.jsx

import currencyFormatter from "../../../utility/currency";
1

There are 1 answers

0
Aniket Pandey On BEST ANSWER

Your import statement is wrong. CurrencyFormatter is not a default export. You need to use named import for this.

Utils/currencyFormatter.js

export let currencyFormatter = new Intl.NumberFormat("en-GB", {
  style: "currency",
  currency: "GBP",
  minimumFractionDigits: 2,
});

component1.js

import {currencyFormatter} from './utils/currencyFormatter.js';

export default function Component1(){
return(
<tbody>
    {data.items.map((item) => (
        <tr key={item} className="text-right">
            <td className="text-left py-4 align-top text-sm">{item.description}</td>
            <td className="py-4 min-w-[100px] align-top text-sm font-bold">{currencyFormatter.format(item.price)} // ERROR HERE!</td>
            <td className="py-4 min-w-[100px] align-top text-sm">{item.quantity}</td>
            <td className="py-4 min-w-[100px] align-top text-sm font-bold">{item.price * item.quantity}</td>
        </tr>
    ))}
</tbody>
)
}