Num
API Reference for the <Num> component
Overview
The <Num> component renders a formatted number string in the user's locale, and can be customized with formatting options.
<Num>{100}</Num>
// Output: 100All reformatting is handled locally using the Intl.NumberFormat library.
Reference
Props
Prop
Type
Description
| Prop | Description |
|---|---|
children | The content to render inside the component. Typically a number, which will be formatted according to the current locale and options. If provided, it takes precedence over the value prop. |
name | Optional name for the number field, used for metadata purposes. |
value | The default value for the number. Can be a string or number. Strings will be parsed into numbers before formatting. |
options | Optional formatting options for the number, following the Intl.NumberFormatOptions specification. Use this to define styles such as currency, decimal precision, etc. |
locales | Optional locales to specify the formatting locale. If not provided, the default user's locale is used. Read more about specifying locales here. |
Returns
JSX.Element containing the formatted number as a string.
Examples
Basic Example
In this example, item.quantity will be reformatted according to the user's locale.
import { Num } from 'gt-react';
export default function Inventory(item) {
return (
<Num> {item.quantity} </Num>
);
}Specifying locales
By default, locales are determined by the user's browser settings,
but you can explicitly set the locale for the <Num> component.
import { Num } from 'gt-react';
export default function CountDisplay(item) {
return (
<Num locales={['fr-FR']}> {item.count} </Num>
);
}Translating <Num> components
Let's say that you want your number to be in a larger sentence that gets translated.
Just add the <T> components around the content.
import { T, Num } from 'gt-react';
export default function DynamicPriceDisplay(item) {
return (
<T id="price">
There are <Num> {item.count} </Num> units available. // [!code highlight]
</T>
);
}Custom formatting
<Num> uses the Intl.NumberFormat library for formatting.
import { Num } from 'gt-react';
export default function CustomFormat(number) {
return (
<Num
options={{ style: "decimal", maximumFractionDigits: 2 }}
>
{number}
</Num>
);
}Notes
- The
<Num>component is used to format numbers according to a user's locale. - When inside of a
<T>component, make sure to wrap all dynamic numbers in a<Num>component.
Next steps
- For more details and usage examples of the
<Num>component and other variable components like<Currency>,<DateTime>, and<Var>,
How is this guide?