Browse docs

API

useFormatter

ReactVanilla

Locale-aware formatting with no state — numbers, dates, lists, and measurement units, all rendered for the active locale. The React binding over @secundus-studio/stift-format; stable per locale.

useFormatter(options?: { units?: Partial<Record<UnitCategory, string>> })

options.units option

  • Type: Partial<Record<UnitCategory, string>>
  • Optional — per-category unit overrides for the unit formatters below. Omit it to follow the effective units (per-locale defaults plus setUnit overrides).

Returns

A FormatterApi. Every method takes values in canonical form and renders for the active locale:

  • number(value, options?) — Intl.NumberFormatOptions.
  • date(value, options?), time(value, options?), dateTime(value, options?) — Date | number | string, Intl.DateTimeFormatOptions.
  • relativeTime(value, unit, options?) — Intl.RelativeTimeFormatUnit.
  • list(values, options?) — Intl.ListFormatOptions.
  • formatLength(value, options?) — base unit meter; formatMass (kilogram), formatArea (hectare), formatTemperature (celsius), formatDigital (byte). Values are always in the category base unit; the active unit comes from the options above, else the effective unit.

Examples

function Price({ amount, currency }: { amount: number; currency: string }) {
  const f = useFormatter()
  return (
    <p>
      {f.number(amount, { style: 'currency', currency })} ·{' '}
      {f.relativeTime(-3, 'day')}
    </p>
  )
}

Next