atozas-traslate
v1.0.2
Published
A React library for automatic UI text translation using Google Translate public endpoint
Maintainers
Readme
atozas-traslate
A React library for automatic UI text translation using Google Translate public endpoint. This package provides a simple and efficient way to translate your app's UI text when users select a different language.
Installation
npm install atozas-traslateFeatures
- 🌍 Automatic text translation based on selected language
- 💾 Language preference stored in localStorage
- ⚡ In-memory caching to avoid repeated API calls
- 🎣 Simple React hooks API
- 🔄 Automatic language restoration on page reload
- 🛡️ Safe error handling with fallback to original text
Usage
1. Wrap Your App with LanguageProvider
First, wrap your React app with the LanguageProvider component:
import React from "react";
import { LanguageProvider } from "atozas-traslate";
function App() {
return (
<LanguageProvider>
{/* Your app components */}
</LanguageProvider>
);
}
export default App;2. Use the useTranslate Hook
Use the useTranslate hook in your components to translate text:
import React from "react";
import { useTranslate } from "atozas-traslate";
function WelcomeMessage() {
const t = useTranslate("Welcome to our app!");
return <h1>{t}</h1>;
}3. Add Language Selector (Automatic - All Languages)
Easiest way: Use the ready-to-use LanguageSelector component. It automatically shows all 100+ Google Translate supported languages:
import React from "react";
import { LanguageSelector } from "atozas-traslate";
function App() {
return (
<LanguageProvider>
<div>
<label>Select Language: </label>
<LanguageSelector />
</div>
{/* Your app content */}
</LanguageProvider>
);
}That's it! The dropdown will automatically show all languages. You can also customize it:
import { LanguageSelector } from "atozas-traslate";
// With custom styling
<LanguageSelector
className="my-custom-select"
onChange={(langCode) => console.log("Language changed to:", langCode)}
/>
// With custom ID
<LanguageSelector id="my-language-picker" />Alternative: Create Custom Language Selector
If you want to create your own language selector, use the useLanguage hook and getAllLanguages:
import React from "react";
import { useLanguage, getAllLanguages } from "atozas-traslate";
function CustomLanguageSelector() {
const { language, setLanguage } = useLanguage();
const languages = getAllLanguages(); // Get all 100+ languages
return (
<select
value={language}
onChange={(e) => setLanguage(e.target.value)}
>
{languages.map((lang) => (
<option key={lang.code} value={lang.code}>
{lang.name}
</option>
))}
</select>
);
}Or use a subset of languages:
import React from "react";
import { useLanguage, SUPPORTED_LANGUAGES } from "atozas-traslate";
function PopularLanguagesSelector() {
const { language, setLanguage } = useLanguage();
// Select specific languages
const popularLanguages = [
{ code: "en", name: SUPPORTED_LANGUAGES["en"] },
{ code: "es", name: SUPPORTED_LANGUAGES["es"] },
{ code: "fr", name: SUPPORTED_LANGUAGES["fr"] },
{ code: "de", name: SUPPORTED_LANGUAGES["de"] },
{ code: "ja", name: SUPPORTED_LANGUAGES["ja"] },
{ code: "zh", name: SUPPORTED_LANGUAGES["zh"] },
{ code: "kn", name: SUPPORTED_LANGUAGES["kn"] }, // Kannada
{ code: "hi", name: SUPPORTED_LANGUAGES["hi"] }, // Hindi
];
return (
<select
value={language}
onChange={(e) => setLanguage(e.target.value)}
>
{popularLanguages.map((lang) => (
<option key={lang.code} value={lang.code}>
{lang.name}
</option>
))}
</select>
);
}Complete Example
Simple example using the ready-to-use LanguageSelector:
import React from "react";
import { LanguageProvider, useTranslate, LanguageSelector } from "atozas-traslate";
function Header() {
const title = useTranslate("Welcome to My App");
const subtitle = useTranslate("Choose your language below");
return (
<header>
<h1>{title}</h1>
<p>{subtitle}</p>
</header>
);
}
function App() {
return (
<LanguageProvider>
<Header />
<div>
<label>Language: </label>
<LanguageSelector />
</div>
</LanguageProvider>
);
}
export default App;Custom language selector example:
import React from "react";
import { LanguageProvider, useTranslate, useLanguage, getAllLanguages } from "atozas-traslate";
function Header() {
const title = useTranslate("Welcome to My App");
const subtitle = useTranslate("Choose your language below");
return (
<header>
<h1>{title}</h1>
<p>{subtitle}</p>
</header>
);
}
function CustomLanguageSelector() {
const { language, setLanguage } = useLanguage();
const languages = getAllLanguages(); // All 100+ languages
return (
<div>
<label>Language: </label>
<select value={language} onChange={(e) => setLanguage(e.target.value)}>
{languages.map((lang) => (
<option key={lang.code} value={lang.code}>
{lang.name}
</option>
))}
</select>
</div>
);
}
function App() {
return (
<LanguageProvider>
<Header />
<CustomLanguageSelector />
</LanguageProvider>
);
}
export default App;API Reference
LanguageProvider
Wrapper component that provides language context to your app.
Props:
children(ReactNode): Your app components
useTranslate(text, sourceLanguage?)
Hook that returns translated text based on the current language.
Parameters:
text(string): Text to translatesourceLanguage(string, optional): Source language code. Default:"auto"
Returns:
string: Translated text (or original text if language is "en" or translation fails)
Example:
const translated = useTranslate("Hello, world!");
const translatedFromSpanish = useTranslate("Hola, mundo!", "es");useLanguage()
Hook that provides access to current language and setter function.
Returns:
{ language: string, setLanguage: (lang: string) => void }
Example:
const { language, setLanguage } = useLanguage();LanguageSelector
Ready-to-use component that automatically displays all Google Translate supported languages in a dropdown. No configuration needed!
Props:
className(string, optional): Additional CSS classes for the select elementid(string, optional): ID attribute for the select element. Default:"atozas-language-selector"onChange(function, optional): Callback function called when language changes. Receives the new language code as parameter- All other standard HTML select element props are supported
Example:
import { LanguageSelector } from "atozas-traslate";
// Simple usage - shows all 100+ languages automatically
<LanguageSelector />
// With custom styling and onChange callback
<LanguageSelector
className="my-select"
onChange={(langCode) => {
console.log("Language changed to:", langCode);
}}
/>translateText(text, sourceLanguage?, targetLanguage?)
Direct function for translating text (useful outside React components).
Parameters:
text(string): Text to translatesourceLanguage(string, optional): Source language code. Default:"auto"targetLanguage(string, optional): Target language code. Default:"en"
Returns:
Promise<string>: Translated text
Example:
import { translateText } from "atozas-traslate";
const translated = await translateText("Hello", "auto", "es");
console.log(translated); // "Hola"Language Utilities
The package exports several utilities for working with languages:
SUPPORTED_LANGUAGES
Object containing all language codes and their names.
import { SUPPORTED_LANGUAGES } from "atozas-traslate";
console.log(SUPPORTED_LANGUAGES['kn']); // "Kannada"
console.log(SUPPORTED_LANGUAGES['hi']); // "Hindi"getLanguageName(code)
Get the name of a language by its code.
Parameters:
code(string): Language code
Returns:
string: Language name or code if not found
Example:
import { getLanguageName } from "atozas-traslate";
getLanguageName('kn'); // "Kannada"
getLanguageName('xyz'); // "xyz"getAllLanguageCodes()
Get all supported language codes as an array (excluding 'auto').
Returns:
Array<string>: Array of language codes
Example:
import { getAllLanguageCodes } from "atozas-traslate";
const codes = getAllLanguageCodes();
// ['af', 'sq', 'am', 'ar', ...]getAllLanguages()
Get all languages as an array of objects with code and name.
Returns:
Array<{code: string, name: string}>: Array of language objects
Example:
import { getAllLanguages } from "atozas-traslate";
const languages = getAllLanguages();
// [{ code: 'af', name: 'Afrikaans' }, { code: 'sq', name: 'Albanian' }, ...]isLanguageSupported(code)
Check if a language code is supported.
Parameters:
code(string): Language code to check
Returns:
boolean: True if supported
Example:
import { isLanguageSupported } from "atozas-traslate";
isLanguageSupported('kn'); // true
isLanguageSupported('xyz'); // falseSupported Languages
This package supports all languages that Google Translate supports. You can access the complete list programmatically:
import { SUPPORTED_LANGUAGES, getAllLanguages } from "atozas-traslate";
// Get all languages as an array
const languages = getAllLanguages();
// Returns: [{ code: 'af', name: 'Afrikaans' }, { code: 'sq', name: 'Albanian' }, ...]
// Access the languages object directly
console.log(SUPPORTED_LANGUAGES['kn']); // "Kannada"Complete Language List
The package includes 100+ languages supported by Google Translate:
af- Afrikaanssq- Albanianam- Amharicar- Arabichy- Armenianaz- Azerbaijanieu- Basquebe- Belarusianbn- Bengalibs- Bosnianbg- Bulgarianca- Catalanceb- Cebuanony- Chichewazh/zh-CN- Chinese (Simplified)zh-TW- Chinese (Traditional)co- Corsicanhr- Croatiancs- Czechda- Danishnl- Dutchen- Englisheo- Esperantoet- Estoniantl- Filipinofi- Finnishfr- Frenchfy- Frisiangl- Galicianka- Georgiande- Germanel- Greekgu- Gujaratiht- Haitian Creoleha- Hausahaw- Hawaiianhe/iw- Hebrewhi- Hindihmn- Hmonghu- Hungarianis- Icelandicig- Igboid- Indonesianga- Irishit- Italianja- Japanesejw- Javanesekn- Kannadakk- Kazakhkm- Khmerko- Koreanku- Kurdish (Kurmanji)ky- Kyrgyzlo- Laola- Latinlv- Latvianlt- Lithuanianlb- Luxembourgishmk- Macedonianmg- Malagasyms- Malayml- Malayalammt- Maltesemi- Maorimr- Marathimn- Mongolianmy- Myanmar (Burmese)ne- Nepalino- Norwegianps- Pashtofa- Persianpl- Polishpt- Portuguesepa- Punjabiro- Romanianru- Russiansm- Samoangd- Scots Gaelicsr- Serbianst- Sesothosn- Shonasd- Sindhisi- Sinhalask- Slovaksl- Slovenianso- Somalies- Spanishsu- Sundanesesw- Swahilisv- Swedishtg- Tajikta- Tamilte- Teluguth- Thaitr- Turkishuk- Ukrainianur- Urduuz- Uzbekvi- Vietnamesecy- Welshxh- Xhosayi- Yiddishyo- Yorubazu- Zulu
Language Helper Functions
import {
getLanguageName,
getAllLanguageCodes,
getAllLanguages,
isLanguageSupported
} from "atozas-traslate";
// Get language name by code
getLanguageName('kn'); // "Kannada"
// Get all language codes
const codes = getAllLanguageCodes(); // ['af', 'sq', 'am', ...]
// Get all languages as objects
const languages = getAllLanguages();
// [{ code: 'af', name: 'Afrikaans' }, ...]
// Check if a language is supported
isLanguageSupported('kn'); // true
isLanguageSupported('xyz'); // falseImportant Notes
⚠️ Warning: This package uses Google Translate's public endpoint, which is unofficial and not officially supported by Google. This means:
- The endpoint may change or become unavailable without notice
- There are no guarantees about rate limits or service availability
- It should not be used for production applications that require reliable translation services
- Consider using official translation APIs for production use
Best Use Cases
This package is ideal for:
- 🎓 Learning apps - Educational applications where translation accuracy is not critical
- 🏢 Internal tools - Company internal applications where free translation is acceptable
- 🎮 Kids apps - Fun applications for children where translation adds value
- 🧪 Prototypes - Quick prototypes and demos that need translation functionality
- 📚 Personal projects - Side projects where you want translation without API costs
How It Works
- When a user selects a language, it's stored in
localStorage - The
useTranslatehook detects the current language - If language is "en", it returns the original text
- Otherwise, it calls the Google Translate endpoint
- Translations are cached in memory to avoid repeated API calls
- On page reload, the language is restored from
localStorage
Requirements
- React 16.8.0 or higher (for hooks support)
- Modern browser with
fetchAPI support
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
