1.1.1 • Published 2 years ago
@knfcz/translator v1.1.1
translator
Installation
Install with
npm install @knfcz/translator
or
yarn add @knfcz/translator
Setup
First you'll need some translation data, here's an example in JSON, but a js object will work too
English:
{
"homePage": {
"title": "Welcome to my website, $name uwu"
}
}
French:
{
"homePage": {
"title": "Bienvenue sur mon site, $name uwu"
}
}
Then, you'll need to create your translator instance, and load your translations
// services/Translator.js
import Translator from '@knfcz/translator';
const frTranslations = require('../lang/fr.json');
const enTranslations = require('../lang/en.json');
const t = new Translator();
// We load our translation data
t.load('fr', frTranslations);
t.load('eng', enTranslations);
// Then we set the current locale to 'fr'
t.setLocale('fr');
export default t;
Usage
All you have to do is call t.get to get the correct translation depending on the current locale
t.get(path: string, params: object, fallbackPath: string): string
Here's an example in a React component:
// pages/Home.jsx
import t from '../services/Translator'
const HomePage = props => {
const name = 'Michel';
return (
<div>
<h1>{t.get('homePage.title', { name })}</h1>
</div>
)
}
This will show "Welcome to my website, Michel uwu" or "Bienvenue sur mon site, Michel uwu" depending on the current locale
Note: In this example, changing the locale will not make any component re-render, if you want this behavior you may consider using a React Context
1.1.1
2 years ago