fast-react-i18n
Version:
Minimalist i18n library for React and Next.js
108 lines (73 loc) β’ 2.97 kB
Markdown
# π 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