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
I did this with nodeJs, after reading your question I made a req via my localhost, hopefully this will help a little.
NodeJs index.js
route.post('/', (req, res) => {
var q = req.body.q;
console.log(q);
var options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
form:
{ key: process.env.TRANSLATE,
q: q,
target: 'en' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
res.send(body);
});
})
ReactJS App.js
class App extends Component {
constructor(props){
super(props);
this.state = {
value: '',
translated: '...'
}
this.translate=this.translate.bind(this);
}
translate(){
axios.post('http://localhost:9000/translate',{q:this.state.value})
.then(data => {
this.setState({translated: data.data.data.translations[0].translatedText})
console.log(data.data.data.translations[0].translatedText)
}).catch(err => {
console.log('error')
})
}
render() {
return (
<div>
<input
value={this.state.value}
onChange={(e)=>this.setState({value: e.target.value})}
type="text"/>
<button onClick={this.translate}>Submit</button>
<h1>{this.state.translated}</h1>
</div>
);
}
}
export default App;
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 :)
Using the users language automatically:
import React from 'react'
export default class Translate extends React.Component{
constructor(props){
super(props)
this.state={
greeting:'I say: "Hello, you all!"',
greeting_in_user_language: null
}
this.userLanguage = navigator.language.slice(0,2)
this.API_KEY = 'YOUR_API_KEY'
this.URL = `https://translation.googleapis.com/language/translate/v2?key=${this.API_KEY}&source=en`
this.URL += `&target=${this.userLanguage}`
}
componentWillMount() {
this.translate( 'greeting_in_user_language', '&q=' + encodeURI(this.state.greeting))
}
translate = (key,string_to_translate) => {
fetch(this.URL+string_to_translate)
.then(res => res.json())
.then(
( res ) => {
let text = res.data.translations[0].translatedText.replace(/("\;)/g,"\"")
this.setState({[key]:text})
}
) .catch(
( error ) => {
console.log("There was an error: ", error);
}
)
}
render() {
return(
<>
<section className="page">
<p>{
this.state.greeting_in_user_language ?
this.state.greeting_in_user_language :
this.state.greeting
}</p>
</section>
</>
)
}
}
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const Convert = ({ text, language }) => {
const [convertedText, setConvertedText] = useState('');
useEffect(() => {
const response = axios
.post(
'https://translation.googleapis.com/language/translate/v2',
{},
{
params: {
q: text,
target: language,
key: 'AIzaSyCHUCmpR7cT_yDFHC98CZJy2LTms-IwDlM'
}
}
)
.then((response) => {
setConvertedText(response.data.data.translations[0].translatedText);
})
.catch((err) => {
console.log('rest api error', err);
});
}, [text, language]);
return <div>{convertedText}</div>;
};
export default Convert;
The 'q' parameter in params object is the text that we want to translate and the 'target' is the language that we want the text to be translated into.
I did this with nodeJs, after reading your question I made a req via my localhost, hopefully this will help a little.
NodeJs index.js
route.post('/', (req, res) => {
var q = req.body.q;
console.log(q);
var options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
form:
{ key: process.env.TRANSLATE,
q: q,
target: 'en' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
res.send(body);
});
})
ReactJS App.js
class App extends Component {
constructor(props){
super(props);
this.state = {
value: '',
translated: '...'
}
this.translate=this.translate.bind(this);
}
translate(){
axios.post('http://localhost:9000/translate',{q:this.state.value})
.then(data => {
this.setState({translated: data.data.data.translations[0].translatedText})
console.log(data.data.data.translations[0].translatedText)
}).catch(err => {
console.log('error')
})
}
render() {
return (
<div>
<input
value={this.state.value}
onChange={(e)=>this.setState({value: e.target.value})}
type="text"/>
<button onClick={this.translate}>Submit</button>
<h1>{this.state.translated}</h1>
</div>
);
}
}
export default App;
Just correcting the typos in the url.
let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}`;
url += '&q=' + encodeURI(text);
url += `&source=${fromLang}`;
url += `&target=${toLang}`;
You can check out this npm package react-translate-with-google-api
© 2022 - 2024 — McMap. All rights reserved.