Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Google Translate customization#2 under NextJS.
Valor Labs profile imageVyacheslav Chub
Vyacheslav Chub forValor Labs

Posted on

     

Google Translate customization#2 under NextJS.

You know, sometimes our first feelings let us down because the world around us is not so simple. I was going to stop withGoogle Translate customization under NextJS. This article reveals an approach to translate any content freely without pain via Google Translate on a NextJS-based project. But a couple of occasions became a game changer.

First, I found one essential improvement regarding language configuration. Second, my colleagueBruno Silva provided me with valuable code improvements. I decided to make a new series by analyzing the factors above. I recommend readingthe previous series if you want to understand my following thoughts.

Let's get started.

The central part of the previous solution ispublic/assets/scripts/lang-config.js contains custom languages settings

window.__GOOGLE_TRANSLATION_CONFIG__={languages:[{title:"English",name:"en"},{title:"Deutsch",name:"de"},{title:"Español",name:"es"},{title:"Français",name:"fr"},],defaultLanguage:"en",};
Enter fullscreen modeExit fullscreen mode

The solution above is legal, but it doesn't look like a NextJS-pure. I found a more elegant way to define global data through NextJS config. Let's addenv section tonext.config.js and removepublic/assets/scripts/lang-config.js

/** @type {import('next').NextConfig} */constnextConfig={reactStrictMode:true,env:{GOOGLE_TRANSLATION_CONFIG:JSON.stringify({languages:[{title:"English",name:"en"},{title:"Deutsch",name:"de"},{title:"Español",name:"es"},{title:"Français",name:"fr"},],defaultLanguage:"en",}),},};module.exports=nextConfig;
Enter fullscreen modeExit fullscreen mode

I also changedpublic/assets/scripts/translation.jsthe following way becausepageLanguage parameter is not mandatory.

functionTranslateInit(){newgoogle.translate.TranslateElement();}
Enter fullscreen modeExit fullscreen mode

According to Bruno's proposal, I encapsulated most of the logic into a custom hook,src/hooks/useLanguageSwitcher.ts.

import{useEffect,useState}from"react";import{parseCookies,setCookie}from"nookies";import{NextPageContext}from"next";exportconstCOOKIE_NAME="googtrans";exportinterfaceLanguageDescriptor{name:string;title:string;}exportinterfaceLanguageConfig{languages:LanguageDescriptor[];defaultLanguage:string;}exporttypeUseLanguageSwitcherResult={currentLanguage:string;switchLanguage:(lang:string)=>()=>void;languageConfig:LanguageConfig|undefined;};exporttypeUseLanguageSwitcherOptions={context?:NextPageContext;};exportconstgetLanguageConfig=():LanguageConfig|undefined=>{letcfg:LanguageConfig|undefined;if(process.env.GOOGLE_TRANSLATION_CONFIG){try{cfg=JSON.parse(process.env.GOOGLE_TRANSLATION_CONFIG??"{}");}catch(e){}}returncfg;};exportconstuseLanguageSwitcher=({context,}:UseLanguageSwitcherOptions={}):UseLanguageSwitcherResult=>{const[currentLanguage,setCurrentLanguage]=useState<string>("");useEffect(()=>{constcfg=getLanguageConfig();constcookies=parseCookies(context);constexistingLanguageCookieValue=cookies[COOKIE_NAME];letlanguageValue="";if(existingLanguageCookieValue){constsp=existingLanguageCookieValue.split("/");if(sp.length>2){languageValue=sp[2];}}if(cfg&&!languageValue){languageValue=cfg.defaultLanguage;}setCurrentLanguage(languageValue);},[]);constswitchLanguage=(lang:string)=>()=>{setCookie(context,COOKIE_NAME,"/auto/"+lang);window.location.reload();};return{currentLanguage,switchLanguage,languageConfig:getLanguageConfig(),};};exportdefaultuseLanguageSwitcher;
Enter fullscreen modeExit fullscreen mode

Important note.process.env.GOOGLE_TRANSLATION_CONFIG allows us to get GOOGLE_TRANSLATION_CONFIG variable from the above mentioned NextJS config.

A couple of final stitches.

src/components/lang-switcher.tsx

import{NextPageContext}from"next";importuseLanguageSwitcher,{LanguageDescriptor,}from"@/hooks/useLanguageSwitcher";importReactfrom"react";exporttypeLanguageSwitcherProps={context?:NextPageContext;};exportconstLanguageSwitcher=({context}:LanguageSwitcherProps={})=>{const{currentLanguage,switchLanguage,languageConfig}=useLanguageSwitcher({context});if(!languageConfig){returnnull;}return(<divclassName="text-center notranslate">{languageConfig.languages.map((ld:LanguageDescriptor,i:number)=>(<React.Fragmentkey={`l_s_${ld}`}>{currentLanguage===ld.name||(currentLanguage==="auto"&&languageConfig.defaultLanguage===ld.name)?(<spanclassName="mx-3 text-orange-300">{ld.title}</span>):(<aonClick={switchLanguage(ld.name)}className="mx-3 text-blue-300 cursor-pointer hover:underline">{ld.title}</a>)}</React.Fragment>))}</div>);};exportdefaultLanguageSwitcher;
Enter fullscreen modeExit fullscreen mode

useLanguageSwitcher looks elegant :)

src/pages/_document.tsx

import{Html,Head,Main,NextScript}from"next/document";importScriptfrom"next/script";exportdefaultfunctionDocument(){return(<Html><Head><Scriptsrc="/assets/scripts/translation.js"strategy="beforeInteractive"/>{process.env.GOOGLE_TRANSLATION_CONFIG&&(<Scriptsrc="//translate.google.com/translate_a/element.js?cb=TranslateInit"strategy="afterInteractive"/>)}</Head><body><Main/><NextScript/></body></Html>);}
Enter fullscreen modeExit fullscreen mode

We don't even physically include the translation engine if the config is missing.

You can find the final solutionhere.

May the Google Translate, NextJS, and Force be with you!

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
kawtharklayshe profile image
kawthar klayshe
  • Joined
• Edited on• Edited

how to add arabic lang? with ar not work correct

CollapseExpand
 
buchslava profile image
Vyacheslav Chub
More than 25 years experienced software enthusiast. Loves a bunch of programming languages and technologies. Writes about tech React, Javascript, Rust...
  • Location
    Kharkiv, Ukraine
  • Education
    https://www.kpi.kharkov.ua/eng/
  • Work
    https://valor-software.com/
  • Joined
• Edited on• Edited

@kawtharklayshe This is a question of RTL support. Please, look atgithub.com/buchslava/nextjs-gtrans...

The solution above is not 100% perfect, but it illustrates how it works.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Modernizing the web with Module Federation and Nx

More fromValor Labs

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp