- Spec files
npm-react-aria
Describes: pkg:npm/react-aria@3.43.x
- Description
- Comprehensive library of unstyled React hooks providing accessible UI primitives with full WAI-ARIA compliance and internationalization support.
- Author
- tessl
- Last updated
internationalization.md docs/
1# Internationalization23Comprehensive internationalization support with locale-aware formatting, RTL layout, and localization utilities. React Aria provides built-in support for over 30 languages with proper cultural adaptations.45## Capabilities67### I18n Provider89Provides internationalization context for the entire application.1011```typescript { .api }12/**13* I18n provider component that sets up locale context14* @param props - I18n provider configuration15* @returns Provider component16*/17function I18nProvider(props: I18nProviderProps): JSX.Element;1819interface I18nProviderProps {20/** Children to provide context to */21children: ReactNode;22/** Current locale */23locale?: string;24/** Map of localized strings */25strings?: LocalizedStrings;26}2728interface LocalizedStrings {29[locale: string]: {30[key: string]: string;31};32}33```3435### Locale Management3637Provides current locale information and utilities.3839```typescript { .api }40/**41* Get current locale information42* @returns Locale information43*/44function useLocale(): {45/** Current locale string (e.g., 'en-US') */46locale: string;47/** Text direction for the locale */48direction: 'ltr' | 'rtl';49};5051/**52* Check if current locale is right-to-left53* @param locale - Locale to check (defaults to current)54* @returns Whether locale is RTL55*/56function isRTL(locale?: string): boolean;5758/**59* Get the text direction for a locale60* @param locale - Locale to check61* @returns Text direction62*/63function getTextDirection(locale: string): 'ltr' | 'rtl';6465/**66* Get the reading direction for a locale67* @param locale - Locale to check68* @returns Reading direction69*/70function getReadingDirection(locale: string): 'ltr' | 'rtl';71```7273### Date Formatting7475Provides locale-aware date and time formatting.7677```typescript { .api }78/**79* Provides locale-aware date formatting80* @param options - Date formatting options81* @returns Date formatter instance82*/83function useDateFormatter(options?: DateFormatterOptions): DateFormatter;8485interface DateFormatterOptions extends Intl.DateTimeFormatOptions {86/** Calendar system to use */87calendar?: string;88}8990interface DateFormatter {91/** Format a date */92format(date: Date): string;93/** Format a date to parts */94formatToParts(date: Date): Intl.DateTimeFormatPart[];95/** Format a date range */96formatRange(startDate: Date, endDate: Date): string;97/** Format a date range to parts */98formatRangeToParts(startDate: Date, endDate: Date): Intl.DateTimeFormatPart[];99/** Get supported locales */100resolvedOptions(): Intl.ResolvedDateTimeFormatOptions;101}102```103104**Usage Examples:**105106```typescript107import { useDateFormatter } from "react-aria";108109function DateDisplay({ date }) {110const formatter = useDateFormatter({111year: 'numeric',112month: 'long',113day: 'numeric'114});115116return <span>{formatter.format(date)}</span>;117}118119// Relative time formatting120function RelativeTime({ date }) {121const formatter = useDateFormatter({122year: 'numeric',123month: 'short',124day: 'numeric',125hour: 'numeric',126minute: 'numeric'127});128129return <time dateTime={date.toISOString()}>{formatter.format(date)}</time>;130}131132// Date range formatting133function DateRange({ startDate, endDate }) {134const formatter = useDateFormatter({135month: 'short',136day: 'numeric'137});138139return <span>{formatter.formatRange(startDate, endDate)}</span>;140}141```142143### Number Formatting144145Provides locale-aware number, currency, and unit formatting.146147```typescript { .api }148/**149* Provides locale-aware number formatting150* @param options - Number formatting options151* @returns Number formatter instance152*/153function useNumberFormatter(options?: Intl.NumberFormatOptions): Intl.NumberFormat;154```155156**Usage Examples:**157158```typescript159import { useNumberFormatter } from "react-aria";160161// Currency formatting162function Price({ amount, currency = 'USD' }) {163const formatter = useNumberFormatter({164style: 'currency',165currency166});167168return <span>{formatter.format(amount)}</span>;169}170171// Percentage formatting172function Percentage({ value }) {173const formatter = useNumberFormatter({174style: 'percent',175minimumFractionDigits: 1176});177178return <span>{formatter.format(value)}</span>;179}180181// Unit formatting182function Distance({ value, unit = 'kilometer' }) {183const formatter = useNumberFormatter({184style: 'unit',185unit,186unitDisplay: 'long'187});188189return <span>{formatter.format(value)}</span>;190}191192// Compact notation193function LargeNumber({ value }) {194const formatter = useNumberFormatter({195notation: 'compact',196compactDisplay: 'short'197});198199return <span>{formatter.format(value)}</span>;200}201```202203### Text Collation204205Provides locale-aware string comparison and sorting.206207```typescript { .api }208/**209* Provides locale-aware string collation210* @param options - Collation options211* @returns Collator instance212*/213function useCollator(options?: Intl.CollatorOptions): Intl.Collator;214```215216**Usage Examples:**217218```typescript219import { useCollator } from "react-aria";220221// Sorting with proper locale collation222function SortedList({ items }) {223const collator = useCollator({224numeric: true,225sensitivity: 'base'226});227228const sortedItems = [...items].sort((a, b) =>229collator.compare(a.name, b.name)230);231232return (233<ul>234{sortedItems.map(item => (235<li key={item.id}>{item.name}</li>236))}237</ul>238);239}240241// Case-insensitive search242function SearchResults({ items, query }) {243const collator = useCollator({244sensitivity: 'base',245ignorePunctuation: true246});247248const filteredItems = items.filter(item =>249collator.compare(item.name.toLowerCase(), query.toLowerCase()) === 0250);251252return (253<ul>254{filteredItems.map(item => (255<li key={item.id}>{item.name}</li>256))}257</ul>258);259}260```261262### Text Filtering263264Provides locale-aware text filtering and searching.265266```typescript { .api }267/**268* Provides locale-aware text filtering269* @param options - Filter options270* @returns Filter function271*/272function useFilter(options?: FilterOptions): Filter;273274interface FilterOptions {275/** Sensitivity level for matching */276sensitivity?: 'base' | 'accent' | 'case' | 'variant';277/** Whether to ignore punctuation */278ignorePunctuation?: boolean;279/** Numeric sorting */280numeric?: boolean;281/** Usage hint for optimization */282usage?: 'sort' | 'search';283}284285interface Filter {286/** Check if text starts with query */287startsWith(text: string, query: string): boolean;288/** Check if text ends with query */289endsWith(text: string, query: string): boolean;290/** Check if text contains query */291contains(text: string, query: string): boolean;292}293```294295### String Localization296297Provides localized string formatting with interpolation.298299```typescript { .api }300/**301* Provides localized string formatting302* @param strings - Localized strings map303* @returns String formatter function304*/305function useLocalizedStringFormatter(strings: LocalizedStrings): LocalizedStringFormatter;306307/**308* Provides message formatting with ICU syntax309* @param locale - Target locale310* @returns Message formatter function311*/312function useMessageFormatter(locale: string): FormatMessage;313314interface LocalizedStringFormatter {315/** Format a localized string with interpolation */316format(key: string, values?: Record<string, any>): string;317}318319type FormatMessage = (320descriptor: { id: string; defaultMessage?: string; description?: string },321values?: Record<string, any>322) => string;323```324325**Usage Examples:**326327```typescript328import { useLocalizedStringFormatter, useMessageFormatter } from "react-aria";329330// Basic string localization331const strings = {332'en-US': {333'welcome': 'Welcome, {name}!',334'items_count': 'You have {count} items'335},336'es-ES': {337'welcome': '¡Bienvenido, {name}!',338'items_count': 'Tienes {count} elementos'339}340};341342function Welcome({ userName, itemCount }) {343const { format } = useLocalizedStringFormatter(strings);344345return (346<div>347<h1>{format('welcome', { name: userName })}</h1>348<p>{format('items_count', { count: itemCount })}</p>349</div>350);351}352353// ICU message formatting354function PluralMessage({ count }) {355const formatMessage = useMessageFormatter('en-US');356357const message = formatMessage({358id: 'item_count',359defaultMessage: '{count, plural, =0 {No items} =1 {One item} other {# items}}'360}, { count });361362return <span>{message}</span>;363}364```365366### RTL Layout Support367368Utilities for handling right-to-left layout and styling.369370```typescript { .api }371/**372* Get appropriate style properties for RTL layouts373* @param props - Style properties to transform374* @param locale - Target locale375* @returns Transformed style properties376*/377function getRTLStyles(props: React.CSSProperties, locale?: string): React.CSSProperties;378379/**380* Transform logical properties for RTL381* @param property - CSS property name382* @param value - CSS property value383* @param direction - Text direction384* @returns Transformed property and value385*/386function transformRTLProperty(387property: string,388value: string | number,389direction: 'ltr' | 'rtl'390): { property: string; value: string | number };391392/**393* Get the start/end properties for a direction394* @param direction - Text direction395* @returns Object with start and end property mappings396*/397function getDirectionalProperties(direction: 'ltr' | 'rtl'): {398start: 'left' | 'right';399end: 'left' | 'right';400};401```402403**Usage Examples:**404405```typescript406import { useLocale, getRTLStyles } from "react-aria";407408// RTL-aware component styling409function DirectionalBox({ children }) {410const { direction } = useLocale();411412const styles = getRTLStyles({413paddingInlineStart: 16,414paddingInlineEnd: 8,415marginInlineStart: 'auto',416borderInlineStartWidth: 2417});418419return (420<div style={styles} dir={direction}>421{children}422</div>423);424}425426// Conditional RTL styling427function FlexContainer({ children }) {428const { direction } = useLocale();429430return (431<div style={{432display: 'flex',433justifyContent: direction === 'rtl' ? 'flex-end' : 'flex-start',434textAlign: direction === 'rtl' ? 'right' : 'left'435}}>436{children}437</div>438);439}440```441442### Calendar Systems443444Support for different calendar systems across cultures.445446```typescript { .api }447/**448* Get supported calendar systems449* @returns Array of supported calendar identifiers450*/451function getSupportedCalendars(): string[];452453/**454* Get the default calendar for a locale455* @param locale - Target locale456* @returns Default calendar identifier457*/458function getDefaultCalendar(locale: string): string;459460/**461* Check if a calendar is supported462* @param calendar - Calendar identifier463* @returns Whether calendar is supported464*/465function isCalendarSupported(calendar: string): boolean;466```467468## Types469470```typescript { .api }471type Locale = string;472473type Direction = 'ltr' | 'rtl';474475interface LocaleInfo {476/** Locale identifier */477locale: Locale;478/** Text direction */479direction: Direction;480/** Language code */481language: string;482/** Country/region code */483region?: string;484/** Script code */485script?: string;486}487488interface DateFormatterOptions extends Intl.DateTimeFormatOptions {489/** Calendar system */490calendar?: string;491/** Number system */492numberingSystem?: string;493/** Time zone */494timeZone?: string;495/** Hour cycle */496hourCycle?: 'h11' | 'h12' | 'h23' | 'h24';497}498499interface LocalizedStrings {500[locale: string]: {501[key: string]: string | ((values: Record<string, any>) => string);502};503}504505interface CollationOptions extends Intl.CollatorOptions {506/** Locale to use for collation */507locale?: string;508/** Custom collation rules */509rules?: string;510}511512interface FilterOptions {513/** Sensitivity for matching */514sensitivity?: 'base' | 'accent' | 'case' | 'variant';515/** Whether to ignore punctuation */516ignorePunctuation?: boolean;517/** Numeric comparison */518numeric?: boolean;519/** Usage optimization */520usage?: 'sort' | 'search';521}522```523524**Supported Locales:**525526React Aria includes built-in support for the following locales:527528- Arabic (ar-AE)529- Bulgarian (bg-BG)530- Czech (cs-CZ)531- German (de-DE)532- Greek (el-GR)533- English (en-US)534- Spanish (es-ES)535- Finnish (fi-FI)536- French (fr-FR)537- Hebrew (he-IL)538- Croatian (hr-HR)539- Hungarian (hu-HU)540- Italian (it-IT)541- Japanese (ja-JP)542- Korean (ko-KR)543- Lithuanian (lt-LT)544- Latvian (lv-LV)545- Norwegian Bokmål (nb-NO)546- Dutch (nl-NL)547- Polish (pl-PL)548- Portuguese (pt-BR)549- Romanian (ro-RO)550- Russian (ru-RU)551- Slovak (sk-SK)552- Slovenian (sl-SI)553- Serbian (sr-SP)554- Swedish (sv-SE)555- Turkish (tr-TR)556- Ukrainian (uk-UA)557- Chinese Simplified (zh-CN)558- Chinese Traditional (zh-TW)559560Each locale includes proper translations for accessibility strings, date/time formatting, and cultural adaptations.