Integrating Google Translate into Your Next.js Website

kstulgys

kstulgys

Posted on February 22, 2024

Integrating Google Translate into Your Next.js Website

In the global digital landscape, offering your website in multiple languages is not just an option—it's a necessity. This tutorial guides you through the seamless integration of Google Translate into a Next.js website, enabling users to switch languages via a dropdown menu. Let's dive into the code essentials to make your website universally accessible.

Implementing the Language Selection Component

We'll start by creating a component that leverages the Google Translate API to offer a dynamic language selection dropdown. The component will automatically detect the user's preferred language, allowing for an intuitive and personalized user experience.

Prerequisites

This tutorial assumes you have a basic understanding of React and Next.js concepts.

Step 1: Setting Up the Component

First, import the necessary modules and define a list of languages you wish to support:

"use client";
import Script from "next/script";
import React from "react";

const languages = [
  { label: "English", value: "en", src: "https://flagcdn.com/h60/us.png" },
  // Add additional languages as needed
];
Enter fullscreen mode Exit fullscreen mode

Step 2: Initializing Google Translate

Implement the function to initialize Google Translate, specifying the languages your site will support:

const includedLanguages = languages.map(lang => lang.value).join(",");

function googleTranslateElementInit() {
  new window.google.translate.TranslateElement({
    pageLanguage: "auto", includedLanguages
  }, "google_translate_element");
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Managing State and Language Selection

Create a React component to manage the selected language and render the UI for language selection:

export function GoogleTranslate({ prefLangCookie }: { prefLangCookie: string }) {

  const [langCookie, setLangCookie] = React.useState(decodeURIComponent(prefLangCookie));

  React.useEffect(() => {
    window.googleTranslateElementInit = googleTranslateElementInit;
  }, []);

  const onChange = (value: string) => {
    const lang = "/en/" + value;
    setLangCookie(lang);
    const element = document.querySelector(".goog-te-combo");
    element.value = value;
    element.dispatchEvent(new Event("change"));
  };

  return (
    <div>
      <div id="google_translate_element" style={{ visibility: "hidden", width: "1px", height: "1px" }}></div>
      <LanguageSelector onChange={onChange} value={langCookie} />
      <Script
        src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"
        strategy="afterInteractive"
      />
    </div>
  );
};

function LanguageSelector({ onChange, value }) {
  const langCookie = value.split("/")[2];
  return (
    <select onChange={(e) => onChange(e.target.value)} value={langCookie}>
      {languages.map((it) => (
        <option value={it.value} key={it.value}>
          {it.label}
        </option>
      ))}
    </select>
  );
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Incorporating Styles to Hide the Default Google Translate Widget

To ensure a cohesive design, apply CSS to hide the default Google Translate widget and only display your custom dropdown:

body { position: "static", top: "0px !important"; }
iframe.skiptranslate { display: "none !important"; }
Enter fullscreen mode Exit fullscreen mode

Step 5: Implementing the Language Cookie

Pass the preferred language cookie from the server component to GoogleTranslate to preserve user language preferences:

<GoogleTranslate prefLangCookie={getPrefLangCookie()}/>
Enter fullscreen mode Exit fullscreen mode
export const getPrefLangCookie = () => {
  return cookies().get("googtrans")?.value ?? "en";
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following these steps, you have now equipped your Next.js website with a powerful feature to attract and retain a global audience by breaking down language barriers. This integration not only enhances user experience but also broadens your website's reach. Happy coding!

💖 💪 🙅 🚩
kstulgys
kstulgys

Posted on February 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related