How to add Google Translator to your Next Js Projects

Google translator is a useful tool for your project. Using this users can easily switch to any preferred language as it does not require any API integration and request call to the server.
Most of the develop consider google translator as the first choice when it comes to applying language options in projects.

Getting started with google translator is also very simple and easy as you don’t need to create any additional API key. In this post, I’ll teach you how to use this in your next js or react js project.

pages\index.js

import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import React, { useContext, useEffect } from 'react'

export default function Home() {

    useEffect(() => {
        var addScript = document.createElement('script');
        addScript.setAttribute('src', '//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit');
        document.body.appendChild(addScript);
        window.googleTranslateElementInit = googleTranslateElementInit;
    }, [])

    const googleTranslateElementInit = () => {

        new window.google.translate.TranslateElement({
            pageLanguage: 'en',
            includedLanguages : "en,ms,ta,zh-CN", // include this for selected languages
            layout: google.translate.TranslateElement.InlineLayout.SIMPLE
        },
        'google_translate_element');

    }

    return (
        <div className={styles.container}>

            <div id="google_translate_element" > </div>

            <div>
                Welcome to Next JS
            </div>

        </div>
    )
}
Output of google translator dropdown in next js
Output of google translator dropdown in next js
Here are useful answers related to Styling google translator

You first need to create a HTML DIV element and give it id=”google_translate_element”. Using the useEffect() hook you can append script tag into the document.
The scrript tag takes a callback function and in this case it is googleTranslateElementInit() and in that function new window.google.translate.TranslateElement object in initialized with options.

  • pageLanguage : This option specifies the default page language.
  • includedLanguages : This option user can specify the languages of choice and it is not specified then all languages will be listed.
  • layout : specifies how the language dropdown to be displayed the available options are HORIZONTAL, SIMPLE, VERTICAL
Summary
Review Date
Reviewed Item
How to add Google Translator to your Next Js Projects
Author Rating
51star1star1star1star1star
Software Name
Next and React JS
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development