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:
npm i google-translate
npm i react-cookies
2) Get ready to create your API key and hide the key so that it doesn’t get pushed onto the internet. In terminal:
3) Sign into Google API Console with your Gmail then create your API key:
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:
.env to line 25, this tells GitHub to ignore pushing your
.env file online.
.env on the top level of the app, Copy your key from Google Console and replace the string “PASTE YOUR KEY HERE”:
8) In terminal:
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
- If you already have a server running, restart it so that
process.env.BLAH_BLAH_BLAHcaptures the most recent change.
10) Preparation is done, we can now build the app. In terminal:
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
12) Run the app. In terminal:
- 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.