5.0.1 • Published 3 years ago

@dbenfouzari/react-native-i18n v5.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

@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 :

OptionDescriptionRequiredDefault
dictionariesThe dictionaries where your localizations are stored. Object key is the language code (en, fr, de) and the value is an object of translationstrue
localeThe default locale. By default, we will search for the user preferred language.falseUser 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

MethodDescription
configure(options: { dictionaries: T, locale: keyof T }) => voidConfiguration method
t(path: keyof Tkeyof T | string, variables?: { key: string: string }) => stringThe method you will call to translate your strings