@metadiv-studio/translation
v0.3.0
Published
A lightweight, non-SSR translation package for React applications. This package provides a simple and efficient way to handle internationalization in client-side React applications with support for multiple languages and automatic language persistence.
Readme
@metadiv-studio/translation
A lightweight, non-SSR translation package for React applications. This package provides a simple and efficient way to handle internationalization in client-side React applications with support for multiple languages and automatic language persistence.
🚀 Installation
npm i @metadiv-studio/translation📖 Description
This package is designed specifically for non-SSR (Client-Side Rendering) React applications that need internationalization support. It provides:
- Lightweight: Minimal bundle size with no heavy dependencies
- Simple API: Easy-to-use context-based translation system
- Language Persistence: Automatically saves language preference to localStorage
- TypeScript Support: Full TypeScript support with proper type definitions
- Multiple Language Support: Built-in support for English, Traditional Chinese (Hong Kong), and Simplified Chinese
- Extensible: Easy to add more languages and customize translation keys
🛠️ Usage
1. Setup Translation Provider
Wrap your app with the TranslationProvider and provide your translation dictionaries:
import { TranslationProvider } from '@metadiv-studio/translation';
// Your translation dictionaries
const enTranslations = {
"hello": "Hello",
"welcome": "Welcome to our app",
"button.submit": "Submit",
"error.notFound": "Page not found"
};
const zhHkTranslations = {
"hello": "你好",
"welcome": "歡迎使用我們的應用程式",
"button.submit": "提交",
"error.notFound": "找不到頁面"
};
const zhCnTranslations = {
"hello": "你好",
"welcome": "欢迎使用我们的应用程序",
"button.submit": "提交",
"error.notFound": "找不到页面"
};
function App() {
return (
<TranslationProvider
defaultLocale="en"
en={enTranslations}
zhHk={zhHkTranslations}
zhCn={zhCnTranslations}
>
<YourAppContent />
</TranslationProvider>
);
}2. Use Translation Hook
Use the useTranslation hook in your components to access translation functions and language state:
import { useTranslation } from '@metadiv-studio/translation';
function WelcomeComponent() {
const { t, language, setLanguage } = useTranslation();
return (
<div>
<h1>{t("welcome")}</h1>
<p>Current language: {language}</p>
<div>
<button onClick={() => setLanguage("en")}>English</button>
<button onClick={() => setLanguage("zh-HK")}>繁體中文</button>
<button onClick={() => setLanguage("zh-CN")}>简体中文</button>
</div>
</div>
);
}3. Advanced Usage Examples
Language Switcher Component
import { useTranslation } from '@metadiv-studio/translation';
function LanguageSwitcher() {
const { language, setLanguage } = useTranslation();
const languages = [
{ code: "en", name: "English" },
{ code: "zh-HK", name: "繁體中文" },
{ code: "zh-CN", name: "简体中文" }
];
return (
<select
value={language}
onChange={(e) => setLanguage(e.target.value)}
>
{languages.map(lang => (
<option key={lang.code} value={lang.code}>
{lang.name}
</option>
))}
</select>
);
}Conditional Rendering Based on Language
import { useTranslation } from '@metadiv-studio/translation';
function LocalizedContent() {
const { t, language } = useTranslation();
return (
<div>
<h2>{t("content.title")}</h2>
{/* Show different content based on language */}
{language === "en" && (
<p>This content is only visible in English</p>
)}
{language.startsWith("zh") && (
<p>此內容僅在中文版本中顯示</p>
)}
<button>{t("button.continue")}</button>
</div>
);
}Nested Translation Keys
import { useTranslation } from '@metadiv-studio/translation';
function FormComponent() {
const { t } = useTranslation();
return (
<form>
<div>
<label>{t("form.name.label")}</label>
<input
type="text"
placeholder={t("form.name.placeholder")}
/>
<span>{t("form.name.help")}</span>
</div>
<div>
<label>{t("form.email.label")}</label>
<input
type="email"
placeholder={t("form.email.placeholder")}
/>
</div>
<button type="submit">{t("form.submit")}</button>
</form>
);
}🔧 API Reference
TranslationProvider Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| children | React.ReactNode | - | React components to wrap |
| defaultLocale | string | "en" | Default language to use |
| en | Record<string, string> | {} | English translations |
| zhHk | Record<string, string> | {} | Traditional Chinese (Hong Kong) translations |
| zhCn | Record<string, string> | {} | Simplified Chinese translations |
useTranslation Hook
Returns an object with the following properties:
| Property | Type | Description |
|----------|------|-------------|
| language | string | Current language code |
| setLanguage | (language: string) => void | Function to change language |
| t | (key: string) => string | Translation function |
🌍 Supported Languages
- English (
en) - Default language - Traditional Chinese - Hong Kong (
zh-HK) - Simplified Chinese (
zh-CN)
💾 Language Persistence
The package automatically saves the user's language preference to localStorage under the key "language". This means:
- Language choice persists across browser sessions
- No need to implement custom persistence logic
- Works seamlessly with the
defaultLocaleprop
🚫 Non-SSR Limitation
Important: This package is designed for client-side React applications only. It uses localStorage and browser APIs that are not available during server-side rendering. If you need SSR support, consider using packages like next-i18next or react-intl.
📝 Best Practices
- Organize Translation Keys: Use dot notation for nested keys (e.g.,
"form.name.label") - Provide Fallbacks: Always provide fallback text for missing translations
- Consistent Naming: Use consistent naming conventions across your translation files
- Type Safety: Consider creating TypeScript interfaces for your translation keys
- Performance: Keep translation objects lightweight and avoid deeply nested structures
🔍 Troubleshooting
Translation Key Not Found
If a translation key is not found, the t() function returns the key itself as a fallback. This helps with debugging and prevents broken UI.
Language Not Persisting
Ensure that:
- The
TranslationProvideris wrapping your entire app - You're calling
setLanguage()with valid language codes - The browser supports localStorage
TypeScript Errors
Make sure you have the latest version of the package and that your tsconfig.json includes the package types.
📄 License
This package is licensed under the UNLICENSED license.
🤝 Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
Happy translating! 🌍✨
