Skip to main content

Introduction

Oneki.js provides an Internationalization library (i18n) to make an application available in multiple languages. This library works with Create React app and Next.js

Configuration

As usual, the configuration is done via src/settings.ts

export default {
i18n: {
locales: ["en", "fr"], // supported locales
defaultLocale: "en",
url: "/locales" // the base URL to retrieve the JSON files with the translations
}
}

Translations

The translations are stored in JSON files in the folders public/locales/{locale}/{namespace}.json

My-App
├─ public
│ ├─ locales
│ │ └─ en
│ │ │ └─ common.json // locales in english
│ │ └─ fr
│ │ │ └─ common.json // locales in french
│ └─ ... // You are free to create your own structure

Example

Here is a very simple example of a translation file:

// content of public/locales/en/common.json
{
"Welcome": "Welcome"
}

// content of public/locales/fr/common.json
{
"Welcome": "Bienvenue"
}

See Translation files for more info

Hooks

useTranslation

To make a component available in multiple languages, you can use the useTranslation hook
This is the main hook that returns a component and a function that are used to translate a content.

const Example: FC = () => {
const [T, t, locale, loading] = useTranslation([namespaces]);

//output <div>Welcome</div> or <div>Bienvenue</div>
return <div><T>Welcome</T></div>
}

See useTranslation for more info

useLocale

This hook returns the current selected language

const locale = useLocale() // -> locale = fr

Example

Here is a very basic example of a component available in multiple languages

import React from 'react'
import { useTranslation } from 'onekijs';

const I18Component = () => {
const [T, t, locale, loading] = useTranslation();
const firstname = "Joe";
return (
<div>><T>Welcome</T> {firstname} !</div>
);
}