Integrating Google Translate into Your Next.js Website
Tags: translation, nextjs
Published: 2024-02-22 13:42:08

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:

```javascript
"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
];
```

## Step 2: Initializing Google Translate

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

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

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

## Step 3: Managing State and Language Selection

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

```javascript
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>
  );
}
```

## 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:

```css
body { position: "static", top: "0px !important"; }
iframe.skiptranslate { display: "none !important"; }
```

## Step 5: Implementing the Language Cookie

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

```javascript
<GoogleTranslate prefLangCookie={getPrefLangCookie()}/>
```

```javascript
export const getPrefLangCookie = () => {
  return cookies().get("googtrans")?.value ?? "en";
};
```

## 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!