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
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With