You can follow the git link for i18n: https://github.com/SeangLeng/i18n.git
Here is the structure of project:
i18next.d.ts
import resources from './resources';
declare module 'i18next' {
interface CustomTypeOptions {
resources: typeof resources;
// if you see an error like: "Argument of type 'DefaultTFuncReturn' is not assignable to parameter of type xyz"
// set returnNull to false (and also in the i18next init options)
// returnNull: false;
}
}
react-app-env.d.ts
// <reference types="react-scripts" />
resource.ts
import translation from '../i18n/en/translation.json';
const resources = {
translation,
} as const;
export default resources;
config.ts
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import translation from './en/translation.json';
import khmerTranslation from './kh/khmerVersion.json'
let lang = localStorage.getItem('lang')
i18next.use(initReactI18next).init({
lng: `${lang}`, // if you're using a language detector, do not define the lng option
debug: true,
load: 'all',
resources: {
en: {
translation,
},
kh: {
translation: khmerTranslation
}
},
// if you see an error like: "Argument of type 'DefaultTFuncReturn' is not assignable to parameter of type xyz"
// set returnNull to false (and also in the i18next.d.ts options)
// returnNull: false,
});
To testing in app.js
import React, { useEffect, Suspense, useState } from 'react';
import logo from './logo.svg';
import './App.css';
import './i18n/config';
import { useTranslation } from 'react-i18next';
import i18next from 'i18next';
function App() {
const { t, i18n } = useTranslation();
const [language, setlanguage] = useState<string>();
const changeLanguageHandler = (lang: string) => {
setlanguage('en');
localStorage.setItem('lang', lang);
window.location.reload();
};
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<div className='buttons'>
<button onClick={() => changeLanguageHandler('kh')}>Change to Khmer</button>
<button onClick={() => changeLanguageHandler('en')}>Change to English</button>
</div>
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<Suspense fallback={<div>Loading...</div>}>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
{t("description")}
</a>
</Suspense>
</header>
</div>
);
}
export default App;