Implementing Google Translate API in NextJS

Farmaan
2 min readJun 21, 2024

--

Google Translate API offers a powerful and easy-to-use solution for translating text between various languages. In this blog, I’ll walk you through the steps to set up and integrate Google Translate API with Next.js, allowing you to seamlessly add translation capabilities to your web application.

Step 1: Create a GoogleTranslate.tsx file in the ‘components/GoogleTranslate’ directory

import React, { useEffect } from 'react';

declare global {
interface Window {
googleTranslateElementInit?: () => void;
google?: any;
}
}

const GoogleTranslate: React.FC = () => {
useEffect(() => {
const addGoogleTranslateScript = () => {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
script.async = true;
document.body.appendChild(script);
};

window.googleTranslateElementInit = () => {
new window.google.translate.TranslateElement(
{ pageLanguage: 'en' },
'google_translate_element'
);
};

addGoogleTranslateScript();

}, []);

return (
<>
<div id="google_translate_element" style={{ zIndex: 1000, position: 'absolute', top: 0, right: 0, }}></div>
</>
);
};

export default GoogleTranslate;

Step 2: Add the below in your ‘layout.tsx

'use client'
import React, { useEffect } from "react";
import Script from "next/script";
import Navbar from "@/components/Navbar/Navbar";

const RootLayout = ({ children }: React.PropsWithChildren) => {

useEffect(() => {

window.googleTranslateElementInit = () => {
new window.google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element');
};

}, []);

return (

<html lang="en-IN">
<head>

{/* Google Translate */}
<Script
src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"
></Script>

{/* Google Translate CSS */}
<link
rel="stylesheet"
type="text/css"
href="https://www.gstatic.com/_/translate_http/_/ss/k=translate_http.tr.26tY-h6gH9w.L.W.O/am=CAM/d=0/rs=AN8SPfpIXxhebB2A47D9J-MACsXmFF6Vew/m=el_main_css"
/>

</head>
<body>

<div id="google_translate_element" style={{ position: 'fixed', right: 0, top: 100, zIndex: 1000, backgroundColor:'rgba(255, 255, 255, 0.7)', borderRadius:'10px', padding:'5px' }}></div>

<Navbar />

</body>
</html>

)
};

export default RootLayout;

After completion, you should see something like below.

Thank you for reading! I hope this guide helps you integrate Google Translate API with your Next.js application effortlessly. If you have any questions or feedback, feel free to reach me out.

--

--