A simple yet powerful localization library for React applications, designed to streamline multi-language support using TypeScript.
- 🌐 Easy setup and integration into existing React projects.
- 🚀 Lightweight and efficient with minimal dependencies.
- 🌍 Supports dynamic language switching and automatic language detection.
- 📚 Seamless translation management through JSON files.
- ⚛️ Fully typed with TypeScript for enhanced development experience.
- 🎨 Customizable to fit various project requirements.
Install react-translang
via npm:
npm install react-translang
Wrap your root component with TranslangProvider
and provide the list of supported languages and default language.
import React from 'react';
import ReactDOM from 'react-dom';
import { TranslangProvider } from 'react-translang';
const App = () => {
const supportedLanguages ={
en: {
greeting: 'Hello!',
farewell: 'Goodbye!',
},
zh: {
greeting: '你好!',
farewell: '再见!',
},
fr: {
greeting: 'Bonjour!',
farewell: 'Au revoir!',
},
};
const defaultLanguage = 'en';
return (
<TranslangProvider languages={supportedLanguages} defaultLanguage={defaultLanguage}>
<YourAppContent />
</TranslangProvider>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Use the useTranslang
hook in your components to access translation functions (t
) and current language (language
).
import React from 'react';
import { useTranslang } from 'react-translang';
import { Button } from '@mui/material';
const ExampleComponent = () => {
const { t, language, setLanguage } = useTranslang();
const handleLanguageChange = () => {
setLanguage(language === 'en' ? 'zh' : 'en');
};
return (
<div>
<h1>{t('greeting')}</h1>
<Button variant="outlined" onClick={handleLanguageChange}>
{t('farewell')}
</Button>
<p>Current Language: {language}</p>
</div>
);
}
export default ExampleComponent;
Place your translation files (en.json
, zh.json
, fr.json
, etc.) in a public directory (public/localize
) with key-value pairs representing translations for each supported language.
{
"greeting": "Hello!",
"farewell": "Goodbye!"
}
{
"greeting": "你好!",
"farewell": "再见!"
}
{
"greeting": "Bonjour!",
"farewell": "Au revoir!"
}
-
languages
:string[]
- Array of supported language codes. -
defaultLanguage
:string
- Default language code.
-
language
:string
- Current selected language. -
setLanguage
:(language: string) => void
- Function to set the current language. -
t
:(key: string) => string
- Function to translate a key into the current language.
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Fork this repository, make your changes, and submit a pull request.
If you encounter any issues or have suggestions, please open an issue on GitHub.