rudra-js

defaultFormatPrice

import { defaultFormatPrice } from '@rudra-js/react';

Call defaultFormatPrice to format a product's price the same way the block does.

defaultFormatPrice(product: Product, locale?: string) => string

Reference

defaultFormatPrice(product, locale?)

Parameters

  • product: The product whose price and currency to format.
  • localeoptional: The language tag to format for, such as en-GB. Defaults to the locale of the machine running it.

Returns

The price as text, such as $174.00 for a USD price in en-US.

Caveats

  • It throws a TypeError when price isn't a finite number. Products that passed productSchema never have one.
  • It formats with Intl.NumberFormat, so each currency gets its own decimal places. A JPY price of 1740 shows as ¥1,740.
  • A locale that isn't a valid language tag, such as en_US, gives the currency code and the plain number, such as USD 174.

Usage

Formatting a price the same way the block does

Show the price of the product on the page with defaultFormatPrice. Pass the same locale to the block.

import type { ComponentSpec, Product } from '@rudra-js/core';
import { RudraComponent, defaultFormatPrice } from '@rudra-js/react';

const locale = 'en-US';

export function ProductPage({
  product,
  spec,
  products,
}: {
  product: Product;
  spec: ComponentSpec;
  products: Product[];
}) {
  return (
    <main>
      <h1>{product.title}</h1>
      <p>{defaultFormatPrice(product, locale)}</p>
      <RudraComponent spec={spec} products={products} locale={locale} />
    </main>
  );
}

The price under the heading and the prices in the block read the same.

To add to the block's format, call defaultFormatPrice inside your own formatPrice. Pass it the locale yourself.