React Native
React Native
Google Translate Text
See more Google Translate Examples
Demonstrates how to use the Cloud Translation API to translate text from one spoken language to another. The example translates from English to Spanish.Chilkat React Native Downloads
import { Http, HttpResponse, JsonObject } from '@chilkat/react-native'
async function chilkatExample() {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// --------------------------------------------------------------------------------
// IMPORTANT:
// Don't forget you need to 1st enable the Cloud Translation API in your Google Developers Console at https://console.cloud.google.com
// --------------------------------------------------------------------------------
// It is assumed we previously obtained an OAuth2 access token.
// This example loads the JSON access token file
const jsonToken = new JsonObject();
try {
jsonToken.loadFile('qa_data/tokens/_googleTranslate.json');
} catch {
console.log('Failed to load _googleTranslate.json');
return;
}
const http = new Http();
http.authToken = jsonToken.stringOf('access_token');
// The following JSON is sent in the request body.
// {
// "q": "The quick brown fox jumped over the lazy dog.",
// "source": "en",
// "target": "es",
// "format": "text"
// }
const json = new JsonObject();
// The following code creates the JSON request body.
json.updateString('q', 'The quick brown fox jumped over the lazy dog.');
json.updateString('source', 'en');
json.updateString('target', 'es');
json.updateString('format', 'text');
json.emitCompact = false;
console.log(json.emit());
const resp = new HttpResponse();
try {
await http.httpJsonAsync('POST', 'https://translation.googleapis.com/language/translate/v2', json, 'application/json', resp);
} catch {
console.log(http.lastErrorText);
return;
}
const jResp = new JsonObject();
resp.getBodyJson(jResp);
jResp.emitCompact = false;
console.log('Response Body:');
console.log(jResp.emit());
const respStatusCode = resp.statusCode;
console.log(`Response Status Code = ${respStatusCode}`);
if (respStatusCode >= 400) {
console.log('Response Header:');
console.log(resp.header);
console.log('Failed.');
return;
}
// Sample JSON response:
// (Sample code for parsing the JSON response is shown below)
// {
// "data": {
// "translations": [
// {
// "translatedText": "El zorro r�pida salt� sobre el perro perezoso."
// }
// ]
// }
// }
let translatedText = '';
let i = 0;
const n = jResp.sizeOfArray('data.translations');
while (i < n) {
jResp.i = i;
translatedText = jResp.stringOf('data.translations[i].translatedText');
console.log(translatedText);
i++;
}
}