0.0.3 • Published 1 year ago
@onekstar/i18n v0.0.3
@onekstar/i18n
install
yarn add @onekstar/i18n
best practice
init i18n
in src/index.tsx
// src/index.tsx
import { initI18n, Locales } from "@onekstar/i18n";
initI18n({ lang: Locales.en_US });
ReactDOM.render(<App />, rootDOM);
create i18n translations array object
// for example: src/i18n/index.ts
export default {
common: {
welcome: ["welcome to my home", "欢迎来我家做客"], // this array must be [english, chinese]
},
};
use useI18n hooks in component
// src/pages/Home.tsx
import { useI18n } from "@onekstar/i18n";
import i18n from "./i18n";
const App = () => {
const { changeLang, t, lang } = useI18n();
return (
<div>
{/* import translations array form ts file */}
<div>{t(i18n.common.hello)}</div>
{/* pass translations array directly */}
<div>{t(["hello", "你好"])}</div>
{/* translations with variables */}
<div>{t(["hello {{name}}", "你好 {{name}}"], { name: "steve" })}</div>
<button onClick={changeLang}>{lang}</button> // toggle lang globally
</div>
);
};
export default App;
API
// Locales
export declare enum Locales {
en_US = "en_US",
zh_CN = "zh_CN",
}
// initI18n: for init i18n with
export declare const initI18n: ({
lang,
native,
}: {
lang?: Locales | undefined; // default to Locales.en_US
native?: boolean | undefined; // is react native? default to false
}) => void;
// useI18n hooks: use i18n in component
export declare const useI18n: () => {
lang: Locales; // current lang
changeLang: () => void; // toggle lang
isEN: boolean; // is current lang english
t: (
arr: string[],
variables?:
| {
[key: string]: any;
}
| undefined
) => string; // return translation auto by current lang
};