DEV Community

Robert Chen
Robert Chen

Posted on • Originally published at Medium on

29 2

How to Use Google Translate API

An easy follow-along tutorial

Prerequisites: Knowledge of React.js will be required for this tutorial.

We’re going to use google-translate library to help connect your app with Google Translate API, the library also provides methods to initiate the translating. We’ll also use react-cookies library to store a user’s chosen language in the browser for the user’s convenience and we’ll store some translated text in a cookie so that the same sentence doesn’t have to be re-translated every time the user loads the app (you have to pay per translation, try to avoid redundant translating).

1) Let’s get started, in terminal:



create-react-app google-translate-demo
cd google-translate-demo
npm i google-translate
npm i react-cookies


Enter fullscreen mode Exit fullscreen mode

2) Get ready to create your API key and hide the key so that it doesn’t get pushed onto the internet. In terminal:



touch .env
open .env


Enter fullscreen mode Exit fullscreen mode

3) Sign into Google API Console with your Gmail then create your API key:

1

2

3

4

5

6

4) After creating the key, DO NOT share it with anyone and ABSOLUTELY DO NOT push that key to GitHub or anywhere online. Any fees accrued using that key will be charged to your account. I know someone who knows someone who owes Amazon $50,000+ because he unknowingly pushed his key to GitHub for only 3 days and someone went on a shopping spree with his key. With that said, now I’ll show you how to safely use and protect your key.

5) In terminal:



open .gitignore


Enter fullscreen mode Exit fullscreen mode

6) Add .env to line 25, this tells GitHub to ignore pushing your .env file online.

# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.env
view raw .gitignore hosted with ❤ by GitHub

7) Create .env on the top level of the app, Copy your key from Google Console and replace the string “PASTE YOUR KEY HERE”:

REACT_APP_GOOGLE_TRANSLATE_API_KEY="PASTE YOUR KEY HERE"
view raw .env hosted with ❤ by GitHub

8) In terminal:



mkdir src/utils
touch src/utils/googleTranslate.js
open src/utils/googleTranslate.js


Enter fullscreen mode Exit fullscreen mode

9) We use your API key through the variable that we created in .env so that your actual key is safe from the public’s eye. In googleTranslate.js:

const apiKey = process.env.REACT_APP_GOOGLE_TRANSLATE_API_KEY;
export const googleTranslate = require("google-translate")(apiKey);
  • If you already have a server running, restart it so that process.env.BLAH_BLAH_BLAH captures the most recent change.

10) Preparation is done, we can now build the app. In terminal:



open App.js


Enter fullscreen mode Exit fullscreen mode

11) We’re going to create a simple select field and translate some text with the google-translate library that’s now connected to your Google Translate API key. In App.js:

import React, { Component } from "react";
import cookie from "react-cookies";
import { googleTranslate } from "./utils/googleTranslate";
class App extends Component {
state = {
languageCodes: [],
language: cookie.load("language") ? cookie.load("language") : "en",
question: cookie.load("question")
? cookie.load("question")
: "What language do you prefer to read with?"
};
componentDidMount() {
// load all of the language options from Google Translate to your app state
googleTranslate.getSupportedLanguages("en", function(err, languageCodes) {
getLanguageCodes(languageCodes); // use a callback function to setState
});
const getLanguageCodes = languageCodes => {
this.setState({ languageCodes });
};
}
render() {
const { languageCodes, language, question } = this.state;
return (
<div style={this.divStyle}>
<p>{question}</p>
{/* iterate through language options to create a select box */}
<select
className="select-language"
value={language}
onChange={e => this.changeHandler(e.target.value)}
>
{languageCodes.map(lang => (
<option key={lang.language} value={lang.language}>
{lang.name}
</option>
))}
</select>
</div>
);
}
changeHandler = language => {
let { question } = this.state;
let cookieLanguage = cookie.load("language");
let transQuestion = "";
const translating = transQuestion => {
if (question !== transQuestion) {
this.setState({ question: transQuestion });
cookie.save("question", transQuestion, { path: "/" });
}
};
// translate the question when selecting a different language
if (language !== cookieLanguage) {
googleTranslate.translate(question, language, function(err, translation) {
transQuestion = translation.translatedText;
translating(transQuestion);
});
}
this.setState({ language });
cookie.save("language", language, { path: "/" });
};
// just some inline css to center our demo
divStyle = {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100vh",
width: "100wh"
};
}
export default App;
view raw App.js hosted with ❤ by GitHub

12) Run the app. In terminal:



npm start


Enter fullscreen mode Exit fullscreen mode

demo

  • Change the language, refresh the page and verify that it loads with the language you last selected.

Congrats! Now that you’ve seen how to set up Google Translate API and use the google-translate + react-cookies libraries, let’s clean up. Go back to Google Console and delete your API key, that’ll guarantee no one else can use your key without your knowledge.


Bring your friends and come learn JavaScript in a fun never before seen way! waddlegame.com

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (4)

Collapse
 
lakhankumawat profile image
StarEpicBoy

But it's not free :(

Collapse
 
jucasoft profile image
jucasoft

maybe you inverted the source code of point 3 with the one at point 7?

Collapse
 
robghchen profile image
Robert Chen

thanks for catching that! ⭐️ i've corrected the order of things now

Collapse
 
abhijeetshikha1 profile image
Abhijeet Shikhar

Please provide in Reactjs hooks also

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay