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 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-google-translate-mj

v1.5.3

Published

A React package for automatic website translation using Google Translate API

Readme

React Google Translate MJ

A lightweight React package for automatic website translation using Google Translate API, with no API key required. This package makes it easy to add multi-language support to your React applications with minimal configuration.

npm license

Features

  • 🌐 Free text translation between any languages
  • 🔑 No API key required
  • ⚡ Lightweight and performant
  • 🎯 Easy-to-use components
  • 🔄 Real-time language switching
  • 📱 Automatic OS language detection
  • 📝 Support for HTML and rich text
  • 🌍 RTL languages support
  • ⚛️ Built for React 18+

Installation

# Using npm
npm install react-google-translate-mj

# Using yarn
yarn add react-google-translate-mj

Quick Start

import { TranslateProvider, TranslateText } from 'react-google-translate-mj';

function App() {
  return (
    <TranslateProvider defaultLanguage="en">
      <h1>
        <TranslateText>Hello World!</TranslateText>
      </h1>
    </TranslateProvider>
  );
}

Components and Hooks

TranslateProvider

The root component that provides translation context.

<TranslateProvider 
  defaultLanguage="en"     // Required: Default language code
  targetLanguage="fr"      // Optional: Initial target language
>
  {/* Your app content */}
</TranslateProvider>

TranslateText

Component to wrap any text that needs translation.

<TranslateText>
  This text will be automatically translated
</TranslateText>

// With HTML content
<TranslateText>
  <p>This is a <strong>formatted</strong> text with <a href="#">link</a></p>
</TranslateText>

useTranslator Hook

Access translation functions and state in your components.

import { useTranslator } from 'react-google-translate-mj';

function LanguageSelector() {
  const { 
    currentLanguage,    // Current active language
    setLanguage,        // Function to change language
    defaultLanguage,    // Default language set in provider
    isTranslating      // Translation status
  } = useTranslator();

  return (
    <select 
      value={currentLanguage} 
      onChange={(e) => setLanguage(e.target.value)}
    >
      <option value="en">English</option>
      <option value="fr">Français</option>
      <option value="es">Español</option>
    </select>
  );
}

useAutoTranslate Hook

Hook for manual text translation.

import { useAutoTranslate } from 'react-google-translate-mj';

function TranslatedText({ text }) {
  const translatedText = useAutoTranslate(text);
  return <p>{translatedText}</p>;
}

Advanced Usage

With React Router

import { TranslateProvider, TranslateText, useTranslator } from 'react-google-translate-mj';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

function Layout() {
  const { setLanguage, currentLanguage } = useTranslator();

  return (
    <div>
      <nav>
        <Link to={`/${currentLanguage}/home`}>
          <TranslateText>Home</TranslateText>
        </Link>
      </nav>
      <select onChange={(e) => setLanguage(e.target.value)} value={currentLanguage}>
        <option value="en">English</option>
        <option value="fr">Français</option>
      </select>
      <Outlet />
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <TranslateProvider defaultLanguage="en">
        <Routes>
          <Route path="/:lang/*" element={<Layout />}>
            {/* Your routes */}
          </Route>
        </Routes>
      </TranslateProvider>
    </BrowserRouter>
  );
}

RTL Language Support

The package automatically handles RTL languages. Just wrap your content with TranslateText:

function Content() {
  const { currentLanguage } = useTranslator();
  
  return (
    <div dir={currentLanguage === 'ar' || currentLanguage === 'fa' ? 'rtl' : 'ltr'}>
      <TranslateText>
        This text will be properly aligned based on the language
      </TranslateText>
    </div>
  );
}

Supported Languages

The package supports all languages available in Google Translate. Common language codes:

  • English: 'en'
  • French: 'fr'
  • Spanish: 'es'
  • German: 'de'
  • Italian: 'it'
  • Portuguese: 'pt'
  • Russian: 'ru'
  • Chinese: 'zh'
  • Japanese: 'ja'
  • Korean: 'ko'
  • Arabic: 'ar'
  • Persian: 'fa'

Performance Optimization

The package includes built-in optimizations:

  • Caches translations to minimize API calls
  • Only translates text when language changes
  • Batches translation requests
  • Minimal re-renders using React.memo

Browser Support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)
  • IE 11 (with appropriate polyfills)

Contributing

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

License

MIT © MJ Hassanzadeh

Support

If you find this package helpful, please consider:

  • Starring the GitHub repository
  • Creating an issue for any bugs or feature requests
  • Contributing to the codebase

Server-Side Implementation

This package now includes server-side translation handling for better security and performance. Here's how to set it up:

Express.js Setup

import express from 'express';
import translateHandler from 'react-google-translate-mj/dist/server/api/translate';

const app = express();
app.use(express.json());

// Add the translation endpoint
app.post('/api/translate', translateHandler);

Next.js Setup

Create a file at pages/api/translate.ts:

import type { NextApiRequest, NextApiResponse } from 'next';
import { serverTranslate } from 'react-google-translate-mj/dist/server/translate';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { text, from, to } = req.body;

    if (!text || !to) {
      return res.status(400).json({ error: 'Missing required parameters' });
    }

    const translatedText = await serverTranslate({
      text,
      from,
      to,
    });

    return res.status(200).json({ translatedText });
  } catch (error) {
    console.error('Translation API error:', error);
    return res.status(500).json({ error: 'Translation failed' });
  }
}

Benefits of Server-Side Translation

  1. Better Security: API requests are made from your server instead of client browsers
  2. Improved Performance: Built-in caching mechanism reduces redundant API calls
  3. Rate Limiting Control: Better control over translation request rates
  4. Error Handling: Centralized error handling and logging
  5. IP Protection: Your server IP is used instead of user IPs