use-google-translate
use-google-translate
is a React library that simplifies the integration of Google Translate into your web application. It provides a custom React hook for managing language translation and localization effortlessly.
Features
- Clean, Simple, and Seamless integration of Google Translate.
- Automatically detect user's language and translate to detected language.
- A function to set the user's peferred language with instant translaton.
- Pass in your website's supported languages.
- Customizable and extensible for your specific needs.
Installation
You can install the use-google-translate
library using npm or yarn:
npm install use-google-translate
yarn add use-google-translate
Usage
import useGoogleTranslate, { FutureText, GoogleLanguage } from 'use-google-translate';
Example
import useGoogleTranslate from 'use-google-translate';
export default function Example() {
const supportedLanguages = {
en: {
code: "en",
name: "English",
isRTL: false,
countryCode: "us"
},
"zh-CN": {
code: "zh-CN",
name: "中文",
isRTL: false,
countryCode: "cn"
},
ar: {
code: "ar",
name: "العربية",
isRTL: true,
countryCode: "sa"
}
}
const futureTexts = [
'This is an alert text that shows after clicking "Show Alert 1", and has been translated in the past for this time.',
{
id: 'show-alert-2', text: 'The is another alert text that shows after clicking "Show Alert 2", and has been translated in the past for this time.'
}
]
const mustTranslate = true
const {
langs,
lang,
isRTL,
detectedCountryCode,
detectedCountryLanguage,
supportsLanguage,
getLanguageData,
getTranslationFutureText,
translate,
translating,
} = useGoogleTranslate(
supportedLanguages,
"en",
"Hello world",
futureTexts,
mustTranslate,
6000
);
const handleAlert1 = () => {
alert(getTranslationFutureText('This is an alert text that shows after clicking "Show Alert 1", and has been translated in the past for this time.'))
}
const handleAlert2 = () => {
alert(getTranslationFutureText('show-alert-2'))
}
return (
<div>
<div style={{display: translating? "none" : "block"}}>
<div className="notranslate">ExampleSiteName</div>
<h1>This is a test content for translation.</h1>
<div>Current language: <span className="notranslate">{lang}</span></div>
<select onChange={(e) => {
translate(e.value)
}}>
{Object.keys(langs || {}).map((lng) => {
if (lng === lang) return null;
return (
<option key={index} value={lang.code}>{lang.name}</option>
)
})}
</select>
<button onClick={handleAlert1}>Show Alert 1</button><br />
<button onClick={handleAlert2}>Show Alert 2</button>
</div>
<div style={{display: !translating? "none" : "block", fontStyle: "italic"}}>...</div>
</div>
)
}