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-edge-translate

v1.2.0

Published

A React translation library using Microsoft Edge translate service with custom translation dictionary support

Downloads

2

Readme

React Edge Translate

A React translation library using Microsoft Edge translate service with custom translation dictionary support. This package provides fast, automatic translation functionality while allowing developers to override poor-quality machine translations with high-quality custom translations.

🚀 Features

  • Lightning Fast Translation: Uses Microsoft Edge's public translate service with batch processing
  • Instant Page Translation: Automatic translation on language selection, just like translate.js
  • Custom Translation Dictionary: Override poor machine translations with high-quality custom translations
  • JSON File Management: Easy-to-edit JSON files for managing custom translations
  • Priority Translation Logic: Custom translations take priority over API translations
  • Developer Tools: Built-in UI for managing, importing, and exporting translation dictionaries
  • Translation Analytics: Track usage of custom vs API translations
  • React Optimized: Built specifically for React with hooks and components
  • Smart Caching: Built-in caching to prevent re-translation and improve performance
  • TypeScript: Full TypeScript support with type definitions
  • Auto DOM Translation: Automatically translate entire pages without manual triggers

📦 Installation

npm install react-edge-translate
# or
yarn add react-edge-translate

🎯 Quick Start

Basic Usage with Custom Translations

import React, { useState } from 'react';
import { useTranslate, TranslationDevTools } from 'react-edge-translate';

function App() {
  const [language, setLanguage] = useState('english');
  
  const { translate, isLoading, addCustomTranslation } = useTranslate({
    from: 'english',
    to: 'chinese_simplified',
    customDictionary: { enabled: true }
  });

  const handleTranslate = async () => {
    const result = await translate('Hello World');
    console.log(result.translatedText); // Uses custom translation if available
    console.log(result.source); // 'custom', 'api', or 'mixed'
  };

  return (
    <div>
      <button onClick={handleTranslate} disabled={isLoading}>
        Translate
      </button>
      
      {/* Developer tools for managing custom translations */}
      <TranslationDevTools 
        from="english" 
        to="chinese_simplified"
        onDictionaryUpdate={(stats) => console.log('Dictionary updated:', stats)}
      />
    </div>
  );
}

Automatic Page Translation with Custom Dictionary

import React, { useState } from 'react';
import { useAutoTranslate, TranslationDevTools } from 'react-edge-translate';

function AutoTranslateApp() {
  const [language, setLanguage] = useState('english');

  const { 
    isTranslating, 
    translationSource,
    getTranslationStats,
    addCustomTranslation 
  } = useAutoTranslate({
    targetLanguage: language,
    sourceLanguage: 'english',
    customDictionary: { enabled: true }
  });

  const stats = getTranslationStats();

  return (
    <div>
      <select value={language} onChange={(e) => setLanguage(e.target.value)}>
        <option value="english">English</option>
        <option value="chinese_simplified">简体中文</option>
        <option value="chinese_traditional">繁體中文</option>
      </select>

      {isTranslating && <p>Translating...</p>}
      
      <div style={{ marginTop: '20px' }}>
        <p>Translation Source: {translationSource}</p>
        <p>Custom Translations: {stats.customCount || 0}</p>
        <p>API Translations: {stats.apiCount || 0}</p>
      </div>

      <div id="content">
        <h1>Welcome to our website</h1>
        <p>This content will be automatically translated!</p>
        <p>Custom translations take priority over API translations.</p>
      </div>

      <TranslationDevTools from="english" to={language} />
    </div>
  );
}

📝 Custom Translation Dictionary System

JSON Dictionary Format

Create translation dictionary files in this format:

{
  "metadata": {
    "version": "1.0.0",
    "lastModified": "2024-06-17T10:30:00.000Z",
    "sourceLanguage": "english",
    "targetLanguage": "chinese_simplified",
    "description": "Custom translations for our website",
    "author": "Development Team"
  },
  "translations": {
    "Hello": "你好",
    "Welcome": "欢迎",
    "Thank you": "谢谢",
    "Good morning": "早上好",
    "Our company": "我们公司",
    "Contact us": "联系我们"
  }
}

Dictionary File Management

import { useTranslationDictionary } from 'react-edge-translate';

function DictionaryManager() {
  const {
    dictionary,
    addTranslation,
    removeTranslation,
    exportTranslations,
    importTranslations,
    getStats
  } = useTranslationDictionary({
    from: 'english',
    to: 'chinese_simplified',
    autoLoad: true
  });

  const handleFileImport = async (event) => {
    const file = event.target.files[0];
    if (file) {
      await importTranslations(file);
    }
  };

  return (
    <div>
      <h3>Dictionary Management</h3>
      <p>Entries: {getStats().entryCount}</p>
      
      <button onClick={() => addTranslation('New text', '新文本')}>
        Add Translation
      </button>
      
      <button onClick={() => exportTranslations()}>
        Export Dictionary
      </button>
      
      <input type="file" accept=".json" onChange={handleFileImport} />
    </div>
  );
}

Priority Translation Logic

The translation system follows this priority order:

  1. Custom Dictionary: Check local JSON translation dictionary first
  2. API Cache: Check if translation was previously fetched from API
  3. Microsoft Edge API: Fetch new translation from Microsoft Edge service
  4. Caching: Cache API results for future use
// Example of translation result with source tracking
const result = await translate(['Hello', 'World', 'Custom text']);
console.log(result);
// {
//   success: true,
//   translatedText: ['你好', '世界', '自定义文本'],
//   source: 'mixed',
//   customCount: 1,  // 'Custom text' from dictionary
//   apiCount: 2      // 'Hello' and 'World' from API
// }

🛠️ Developer Tools Component

The TranslationDevTools component provides a UI for managing custom translations:

import { TranslationDevTools } from 'react-edge-translate';

<TranslationDevTools
  from="english"
  to="chinese_simplified"
  className="my-dev-tools"
  onDictionaryUpdate={(stats) => {
    console.log(`Dictionary now has ${stats.entryCount} entries`);
  }}
/>

Features:

  • Add new custom translations
  • Import/export dictionary files
  • View translation statistics
  • Download example dictionary templates
  • Real-time dictionary management

📁 File Structure for Custom Translations

Recommended project structure:

your-project/
├── public/
│   └── translations/
│       ├── english-chinese_simplified.json
│       ├── english-chinese_traditional.json
│       └── example-translations.json
├── src/
│   └── components/
│       └── TranslationManager.tsx
└── package.json

Load custom dictionaries:

const { loadCustomDictionary } = useTranslate({
  customDictionary: {
    enabled: true,
    dictionaryPath: './translations/english-chinese_simplified.json'
  }
});

🔧 Advanced Configuration

Custom Dictionary Configuration

import { edgeTranslator } from 'react-edge-translate';

// Configure the translation system
edgeTranslator.configureDictionary({
  enabled: true,
  fallbackToAPI: true,
  autoReload: true,
  cacheTimeout: 300000 // 5 minutes
});

File Manager Configuration

import { translationFileManager } from 'react-edge-translate';

translationFileManager.updateConfig({
  baseUrl: './custom-translations/',
  autoSave: true,
  validateOnLoad: true
});

📊 Translation Analytics

Track translation usage and performance:

function TranslationAnalytics() {
  const { getTranslationStats } = useAutoTranslate({
    targetLanguage: 'chinese_simplified'
  });

  const stats = getTranslationStats();

  return (
    <div>
      <h3>Translation Statistics</h3>
      <p>Custom Dictionary Entries: {stats.entryCount}</p>
      <p>Custom Translations Used: {stats.customCount || 0}</p>
      <p>API Translations Used: {stats.apiCount || 0}</p>
      <p>Last Updated: {stats.lastModified}</p>
    </div>
  );
}

📚 API Reference

useTranslate(options?)

Enhanced translation hook with custom dictionary support.

Parameters

  • options.from: Source language (default: 'english')
  • options.to: Target language (default: 'chinese_simplified')
  • options.cacheResults: Enable caching (default: true)
  • options.customDictionary.enabled: Enable custom dictionary (default: true)
  • options.customDictionary.dictionaryPath: Path to custom dictionary file
  • options.customDictionary.autoReload: Auto-reload dictionary (default: true)

Returns

  • translate: Function to translate text with custom dictionary priority
  • isLoading: Loading state
  • error: Error message if translation fails
  • addCustomTranslation: Add custom translation to dictionary
  • getTranslationStats: Get dictionary statistics
  • exportDictionary: Export current dictionary
  • loadCustomDictionary: Load custom dictionary from path

useAutoTranslate(options)

Automatic page translation with custom dictionary support.

Parameters

  • targetLanguage: Target language for translation
  • sourceLanguage: Source language (default: 'english')
  • customDictionary: Custom dictionary configuration
  • enabled: Enable/disable auto-translation (default: true)

Returns

  • translatePage: Manually trigger page translation
  • isTranslating: Loading state
  • translationSource: Source of last translation ('custom', 'api', 'mixed')
  • addCustomTranslation: Add custom translation
  • getTranslationStats: Get translation statistics

useTranslationDictionary(options)

Comprehensive dictionary management hook.

Parameters

  • from: Source language
  • to: Target language
  • autoLoad: Auto-load dictionary on mount (default: true)
  • dictionaryPath: Path to dictionary file

Returns

  • dictionary: Current dictionary object
  • addTranslation: Add new translation
  • removeTranslation: Remove translation
  • importTranslations: Import from file
  • exportTranslations: Export to file
  • getStats: Get dictionary statistics

TranslationDevTools

Developer tools component for dictionary management.

Props

  • from: Source language (default: 'english')
  • to: Target language (default: 'chinese_simplified')
  • className: Custom CSS class
  • style: Custom styles
  • onDictionaryUpdate: Callback when dictionary is updated

🌍 Supported Languages

  • english: English
  • chinese_simplified: 简体中文 (Simplified Chinese)
  • chinese_traditional: 繁體中文 (Traditional Chinese)

💡 Best Practices

1. Dictionary Organization

{
  "translations": {
    // UI Elements
    "Login": "登录",
    "Logout": "登出",
    "Submit": "提交",

    // Navigation
    "Home": "首页",
    "About": "关于我们",
    "Contact": "联系我们",

    // Business Terms
    "Our company": "我们公司",
    "Premium service": "高级服务"
  }
}

2. Team Collaboration

  1. Version Control: Store dictionary files in your repository
  2. Review Process: Review custom translations before merging
  3. Consistency: Use consistent terminology across dictionaries
  4. Documentation: Document translation decisions and context

3. Performance Optimization

// Preload dictionaries for better performance
useEffect(() => {
  edgeTranslator.loadCustomDictionary('english', 'chinese_simplified');
}, []);

// Use batch translation for multiple texts
const texts = ['Hello', 'World', 'Welcome'];
const result = await translate(texts); // More efficient than individual calls

4. Error Handling

const { translate, error, clearError } = useTranslate({
  customDictionary: { enabled: true }
});

if (error) {
  console.error('Translation error:', error);
  clearError(); // Clear error state
}

🔧 Development Workflow

  1. Setup: Install the package and create initial dictionary files
  2. Development: Use TranslationDevTools to add custom translations
  3. Export: Export dictionaries for review and version control
  4. Deploy: Include dictionary files in your build process
  5. Monitor: Track translation usage and update dictionaries as needed

🚀 Migration from v1.1.0

If you're upgrading from v1.1.0, here are the key changes:

// Old way (v1.1.0)
const { translate } = useTranslate();

// New way (v1.2.0) - with custom dictionary support
const { translate, addCustomTranslation } = useTranslate({
  customDictionary: { enabled: true }
});

// Add custom translations
addCustomTranslation('Hello', '你好');

📄 License

MIT

🤝 Contributing

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