Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use google translation api with react

I've looked through the docs on the website but there are no examples how to use the google translation api with a react project. Does anyone know how to integrate this so I can just make a simple translation call to the API? Thanks

like image 884
cbutler Avatar asked Jan 03 '23 18:01

cbutler


1 Answers

So with Gregory's help to realize google translate just uses a REST API, I got this working by making a simple call using fetch. In case others are trying to do the same I will add some code here:

let fromLang = 'en';
let toLang = 'no'; // translate to norwegian
let text = 'something to translate';

const API_KEY = [YOUR_API_KEY];

let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}`;
url += '&q=' + encodeURI(text);
url += `&source=${fromLang}`;
url += `&target=${toLang}`;

fetch(url, { 
  method: 'GET',
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json"
  }
})
.then(res => res.json())
.then((response) => {
  console.log("response from google: ", response);
})
.catch(error => {
  console.log("There was an error with the translation request: ", error);
});

Here you can do something with the response.

Hope this helps someone out and thanks Gregory for the most obvious help :)

like image 157
cbutler Avatar answered Jan 11 '23 03:01

cbutler