npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-easy-translate

v1.0.0

Published

Zero-setup React translation library with instant language switching

Readme

React Easy Translate

Zero-setup React translation library with instant language switching.

Author

Shivom Verma
Full Stack Developer & Open Source Contributor

  • 🌐 Building developer-friendly tools and libraries
  • 🚀 Passionate about React, TypeScript, and internationalization
  • 📧 Contact: GitHub Profile
  • 💼 Specializing in zero-configuration solutions for developers

Features

  • 🚀 Zero configuration - works immediately
  • 🔄 Instant language switching
  • 📁 Auto-detects translation files
  • 🔧 Parameter interpolation {{name}}
  • 🌍 Nested keys with dot notation
  • 📦 Lightweight (< 5KB)
  • 🎯 TypeScript ready

Installation

npm install react-easy-translate

Quick Start

1. Wrap your app with TranslationProvider

import React from 'react';
import { TranslationProvider } from 'react-easy-translate';
import App from './App';

function Root() {
  return (
    <TranslationProvider>
      <App />
    </TranslationProvider>
  );
}

export default Root;

2. Create translation files (Flexible Location)

The library automatically detects translation files from multiple locations. Just create JSON files in any of these folders:

  • public/translations/ (Default)
  • public/locales/ (Common i18n folder)
  • public/i18n/ (Alternative i18n folder)
  • src/translations/ (Source folder)
  • assets/translations/ (Assets folder)
  • Or specify a custom path in configuration

public/translations/en.json

{
  "welcome": "Welcome",
  "hello": "Hello {{name}}!",
  "nav": {
    "home": "Home",
    "about": "About",
    "contact": "Contact"
  },
  "messages": {
    "success": "Operation completed successfully",
    "error": "Something went wrong"
  }
}

public/translations/es.json

{
  "welcome": "Bienvenido",
  "hello": "¡Hola {{name}}!",
  "nav": {
    "home": "Inicio",
    "about": "Acerca de",
    "contact": "Contacto"
  },
  "messages": {
    "success": "Operación completada exitosamente",
    "error": "Algo salió mal"
  }
}

public/translations/hi.json (Hindi)

{
  "welcome": "स्वागत है",
  "hello": "नमस्ते {{name}}!",
  "nav": {
    "home": "होम",
    "about": "हमारे बारे में",
    "contact": "संपर्क"
  },
  "messages": {
    "success": "कार्य सफलतापूर्वक पूरा हुआ",
    "error": "कुछ गलत हुआ"
  }
}

public/translations/bn.json (Bengali)

{
  "welcome": "স্বাগতম",
  "hello": "নমস্কার {{name}}!",
  "nav": {
    "home": "হোম",
    "about": "আমাদের সম্পর্কে",
    "contact": "যোগাযোগ"
  },
  "messages": {
    "success": "কাজ সফলভাবে সম্পন্ন হয়েছে",
    "error": "কিছু ভুল হয়েছে"
  }
}

public/translations/ta.json (Tamil)

{
  "welcome": "வரவேற்கிறோம்",
  "hello": "வணக்கம் {{name}}!",
  "nav": {
    "home": "முகப்பு",
    "about": "எங்களைப் பற்றி",
    "contact": "தொடர்பு"
  },
  "messages": {
    "success": "வேலை வெற்றிகரமாக முடிந்தது",
    "error": "ஏதோ தவறு நடந்தது"
  }
}

3. Use translations anywhere

import React from 'react';
import { useTranslation } from 'react-easy-translate';

function MyComponent() {
  const { t, setLanguage } = useTranslation();

  return (
    <div>
      <h1>{t('welcome')}</h1>
      <p>{t('hello', { name: 'John' })}</p>
      <button onClick={() => setLanguage('es')}>Español</button>
    </div>
  );
}

API Reference

TranslationProvider

The main provider component that wraps your app.

<TranslationProvider config={config}>
  {children}
</TranslationProvider>

Props

| Prop | Type | Default | Description | |------|------|---------|-------------| | children | ReactNode | - | Your app components | | config | TranslationConfig | {} | Configuration object |

TranslationConfig

interface TranslationConfig {
  defaultLanguage?: string;      // Default: 'en'
  fallbackLanguage?: string;     // Default: 'en'
  translationsPath?: string;     // Custom path (e.g., '/locales')
  translationsFolder?: string;   // Custom folder name (e.g., 'mylang')
  apiEndpoint?: string;          // Optional API endpoint
  apiHeaders?: Record<string, string>; // Optional API headers
}

useTranslation Hook

Hook to access translation functions and state.

const { t, currentLanguage, setLanguage, isLoading } = useTranslation();

Returns

| Property | Type | Description | |----------|------|-------------| | t | (key: string, params?: object) => string | Translation function | | currentLanguage | string | Current active language | | setLanguage | (language: string) => void | Function to change language | | getSupportedLanguages | () => Promise<string[]> | Get available languages | | getLoadedLanguages | () => string[] | Get loaded languages |

Direct Import Usage

For even simpler usage, import t directly without any provider:

// Option 1: Direct import (no provider needed)
import { 
  t, 
  setLanguage, 
  setPath, 
  getSupportedLanguages,
  getLoadedLanguages 
} from 'react-easy-translate';

// Set custom translation path (optional)
setPath('/my-translations');

// Get available languages
const supportedLangs = await getSupportedLanguages();
console.log('Available languages:', supportedLangs); // ['en', 'es', 'fr']

// Get loaded languages
const loadedLangs = getLoadedLanguages();
console.log('Loaded languages:', loadedLangs); // ['en']

// Use anywhere - components, utils, services
function MyComponent() {
  return <h1>{t('welcome')}</h1>;
}

// Change language directly
setLanguage('es');
// Option 2: With React Context (recommended for complex apps)
import { useTranslation } from 'react-easy-translate';

function MyComponent() {
  const { t, setLanguage } = useTranslation();
  return <h1>{t('welcome')}</h1>;
}

Advanced Usage

Custom Configuration

import { TranslationProvider } from 'react-easy-translate';

const config = {
  defaultLanguage: 'es',
  fallbackLanguage: 'en',
  translationsPath: '/locales',
  apiEndpoint: 'https://api.example.com/translations',
  apiHeaders: {
    'Authorization': 'Bearer your-token',
    'Content-Type': 'application/json'
  }
};

function App() {
  return (
    <TranslationProvider config={config}>
      {/* Your app */}
    </TranslationProvider>
  );
}

API Integration

When using API integration, the expected response format should be:

{
  "welcome": "Welcome",
  "hello": "Hello {{name}}!",
  "nav": {
    "home": "Home",
    "about": "About"
  }
}

The library will automatically fetch from: ${apiEndpoint}?lang=${language}

Parameter Interpolation

Use {{paramName}} in your translation strings:

{
  "greeting": "Hello {{name}}, you have {{count}} messages",
  "price": "Price: ${{amount}}"
}
t('greeting', { name: 'John', count: 5 })
// Output: "Hello John, you have 5 messages"

t('price', { amount: 29.99 })
// Output: "Price: $29.99"

Nested Keys

Access nested translation keys using dot notation:

{
  "user": {
    "profile": {
      "title": "User Profile",
      "fields": {
        "name": "Full Name",
        "email": "Email Address"
      }
    }
  }
}
t('user.profile.title')           // "User Profile"
t('user.profile.fields.name')     // "Full Name"
t('user.profile.fields.email')    // "Email Address"

Language Detection & Switching

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-easy-translate';

function LanguageSwitcher() {
  const { currentLanguage, setLanguage, getSupportedLanguages } = useTranslation();
  const [availableLanguages, setAvailableLanguages] = useState([]);

  useEffect(() => {
    // Auto-detect available languages
    getSupportedLanguages().then(setAvailableLanguages);
  }, []);

  const languageNames = {
    // International Languages
    en: 'English',
    es: 'Español', 
    fr: 'Français',
    de: 'Deutsch',
    it: 'Italiano',
    pt: 'Português',
    ru: 'Русский',
    ja: '日本語',
    ko: '한국어',
    zh: '中文',
    ar: 'العربية',
    tr: 'Türkçe',
    
    // Indian Languages
    hi: 'हिन्दी',
    bn: 'বাংলা',
    te: 'తెలుగు',
    mr: 'मराठी',
    ta: 'தமிழ்',
    ur: 'اردو',
    gu: 'ગુજરાતી',
    kn: 'ಕನ್ನಡ',
    ml: 'മലയാളം',
    or: 'ଓଡ଼ିଆ',
    pa: 'ਪੰਜਾਬੀ',
    as: 'অসমীয়া',
    mai: 'मैथिली',
    ne: 'नेपाली',
    sa: 'संस्कृत',
    ks: 'कॉशुर',
    sd: 'سنڌي',
    kok: 'कोंकणी',
    mni: 'মৈতৈলোন্'
  };

  return (
    <select 
      value={currentLanguage} 
      onChange={(e) => setLanguage(e.target.value)}
    >
      {availableLanguages.map(lang => (
        <option key={lang} value={lang}>
          {languageNames[lang] || lang}
        </option>
      ))}
    </select>
  );
}

Direct Language Detection

import { getSupportedLanguages, getLoadedLanguages } from 'react-easy-translate';

// Get all available languages (async - checks files)
const available = await getSupportedLanguages();
console.log('Available:', available); // ['en', 'es', 'fr']

// Get currently loaded languages (sync)
const loaded = getLoadedLanguages();
console.log('Loaded:', loaded); // ['en']

Loading States

function MyComponent() {
  const { t, isLoading } = useTranslation();

  if (isLoading) {
    return <div>Loading translations...</div>;
  }

  return <h1>{t('welcome')}</h1>;
}

Flexible File Structure

The library automatically detects translation files from multiple locations:

your-project/
├── public/
│   ├── translations/     ← Default location
│   │   ├── en.json
│   │   └── es.json
│   ├── locales/         ← Alternative location
│   │   ├── en.json
│   │   └── es.json
│   └── i18n/            ← Another alternative
│       ├── en.json
│       └── es.json
├── src/
│   ├── translations/    ← Source folder option
│   │   ├── en.json
│   │   └── es.json
│   ├── App.jsx
│   └── index.js
└── package.json

Auto-Detection Order

The library tries to load translations in this order:

  1. Custom translationsPath (if specified)
  2. /translations/ (Default)
  3. /locales/ (Common i18n folder)
  4. /i18n/ (Alternative i18n folder)
  5. /src/translations/ (Source folder)
  6. /assets/translations/ (Assets folder)

Custom Path Examples

// Method 1: Using TranslationProvider config
<TranslationProvider config={{ translationsPath: '/locales' }}>
  <App />
</TranslationProvider>

// Method 2: Direct path setting (no provider needed)
import { setPath, t } from 'react-easy-translate';

// Set single path
setPath('/my-translations');

// Set multiple paths (tries in order)
setPath(['/translations', '/locales', '/i18n']);

// Set path with custom structure
setPath('/assets/lang');

// Then use anywhere
const welcomeText = t('welcome');

Best Practices

  1. Organize translations logically: Use nested objects to group related translations
  2. Use descriptive keys: Make translation keys self-explanatory
  3. Provide fallbacks: Always have a fallback language (usually English)
  4. Handle missing translations: The library returns the key if translation is not found
  5. Use parameters wisely: Keep parameter names simple and consistent

TypeScript Support

The library is fully typed. Import types as needed:

import { TranslationConfig, TranslationResponse } from 'react-easy-translate';

const config: TranslationConfig = {
  defaultLanguage: 'en',
  fallbackLanguage: 'en'
};

Troubleshooting

Translations not loading

  • Check that JSON files are in the correct path (public/translations/)
  • Verify JSON syntax is valid
  • Check browser network tab for 404 errors

API translations not working

  • Verify API endpoint is accessible
  • Check API response format matches expected structure
  • Verify API headers and authentication

Missing translations

  • Check translation key exists in JSON file
  • Verify nested key path is correct
  • Check fallback language has the translation

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT © Shivom Verma

Author

Shivom Verma

  • GitHub: @shivomv
  • Specializes in: React, TypeScript, Developer Tools
  • Focus: Zero-configuration libraries and internationalization solutions

Star this repo if it helped you!