5.0.1 • Published 3 years ago
@dbenfouzari/react-native-i18n v5.0.1
@dbenfouzari/react-native-i18n
// src/i18n/dictionaries/en.json
{
"hello-world": "Hello, World!",
}
// src/i18n/dictionaries/fr.json
{
"hello-world": "Salut à tous !",
}
// src/i18n/index.ts
import I18n from "@dbenfouzari/react-native-i18n";
import en from "./dictionaries/en.json";
import fr from "./dictionaries/fr.json";
const dictionaries = { en, fr } as const;
const i18n = new I18n<typeof dictionaries>();
i18n.configure({ dictionaries });
export default i18n;
// src/App.tsx
import React from "react";
import { Text, View } from "react-native";
import i18n from "./i18n";
const App = () => (
<View style={{ marginTop: 96 }}>
<Text>{i18n.t("hello-world")}</Text>
</View>
);
export default App;
Installation
Install it with
$ yarn add @dbenfouzari/react-native-i18n react-native-localize
Configuration
You must configure this package to be able to use it.
Create a file :
import I18n from "@dbenfouzari/react-native-i18n";
import en from "./dictionaries/en.json";
import fr from "./dictionaries/fr.json";
const dictionaries = { en, fr } as const;
const i18n = new I18n<typeof dictionaries>();
i18n.configure({ dictionaries });
export default i18n;
Configuration options
You can pass some options to i18n.configure
:
Option | Description | Required | Default |
---|---|---|---|
dictionaries | The dictionaries where your localizations are stored. Object key is the language code (en, fr, de) and the value is an object of translations | true | |
locale | The default locale. By default, we will search for the user preferred language. | false | User preferred language |
Usage
Now you can import your i18n and get your translation with
import i18n from "./i18n";
const myTranslatedKey = i18n.t("hello-world"); // Hello, World!
Variables
You can use variables in your translations like this :
{
"greetings": "Hi {{name}}"
}
And in your JavaScript :
const myTranslatedKey = i18n.t("greetings", { name: "John Doe" });
You will get Hi John Doe
API
Method | Description |
---|---|
configure(options: { dictionaries: T, locale: keyof T }) => void | Configuration method |
t(path: keyof Tkeyof T | string, variables?: { key: string: string }) => string | The method you will call to translate your strings |