UNPKG

fast-react-i18n

Version:
108 lines (73 loc) β€’ 2.97 kB
# 🌍 fast-react-i18n Minimalist internationalization library for React with support for language detection, fallback, in-memory/localStorage caching, and dynamic loading of translations from JSON files. --- ## ✨ Characteristics - βœ… Dynamic loading of translation files (/es.json, /en.json, etc.) - 🌐 Automatic detection of the user’s language (?lang, cookies, browser) - πŸ’Ύ In-memory cache and optional persistence via localStorage - πŸ“‰ Automatic fallback if the language is not found - ⚑ Quick access hooks: useTranslation, useForceReloadTranslations, etc. - 🧽 Cache clearing function: clearTranslationsCache - 🌎 Loading available languages via locales.json --- ## πŸš€ Instalation ```bash npm install fast-react-i18n ``` ## πŸ“¦ Expected translations structure ```bash public/ └── locales/ β”œβ”€β”€ en.json β”œβ”€β”€ es.json └── locales.json ← ["en", "es"...] ``` ## 🧩 Basic usage 1. Envolve your App ```bash import { I18nProvider } from "fast-react-i18n"; <I18nProvider initialLocale="auto" fallbackLocale="en" translationsPath="/locales" persist > <App /> </I18nProvider> ``` 2. Access translations ```bash import { useTranslation } from "fast-react-i18n"; export const Home = () => { const { translations } = useTranslation(); return <h1>{translations.home?.title}</h1>; }; ``` ## πŸ›  API ```bash <I18nProvider /> | Propiedad | Tipo | DescripciΓ³n | |---------------------|-----------|---------------------------------------------------------------------------| | `initialLocale` | `string?` | Initial Lang (`"en"`, `"es"`... default `"auto"`) | | `fallbackLocale` | `string?` | Alternative language if the primary one fails | | `translationsPath` | `string` | Base path to your translation files (e.g., /locales) | | `persist` | `boolean?`| Whether to save in localStorage (default: false) | ``` ## Functions ### useForceReloadTranslations() Manually reloads the current language. ### detectUserLocale() Detects the user’s preferred language, in this order: - Query param ?lang= - Cookie lang= - navigator.language - "en" (by default) ### clearTranslationsCache() Deletes from localStorage all translations stored under keys starting with i18n\_. ### loadAvailableLocales(path: string): Promise<string[]> Loads an array with the languages defined in locales.json. ## πŸ’‘ Best practices Use nested objects for your translations ({ home: { title: "" } }) Control the language with setLocale if you need to change it manually Clear the cache if translations change dynamically (e.g., from a CMS) Use fallbackLocale to avoid errors if a file is missing