5

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

cbutler
  • 1,111
  • 5
  • 16
  • 32
  • Google translate just uses a REST api. This can be used independently of whatever frontend framework you are using. When are you wanting to make the call to the api? – Gregory Sims Feb 27 '18 at 20:21
  • Right now I am just trying to get it to work at all. I have tried adding different script tags and code to my index.html file but I really want to make a call to the API from a component in my app. no luck so far. Looking at the google cloud samples there are setup instructions for several languages but not react.. – cbutler Feb 27 '18 at 20:47
  • Ahhh maybe I can just use fetch to make a call using an API key.. – cbutler Feb 27 '18 at 21:03

6 Answers6

8

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 :)

Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
cbutler
  • 1,111
  • 5
  • 16
  • 32
  • If you're just wanting to translate when the page loads, you can put the call in the componentWillMount method and store the result in state and use that state in your render – Gregory Sims Feb 28 '18 at 22:51
  • key and target inside url lack of an equal sign(=) in order to work properly. Apart from that perfect solution – Carlos Hernández Gil Jul 03 '19 at 10:41
  • 1
    thanks man! I was looking for an option to simply use rest API in chrome extension (without client libs and etc), and this is a single piece of code that works and even presented on web You saved me couple hours of worked & reverse engineering !! – Vladyslav Didenko Jan 31 '21 at 13:34
2

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(/(&quot\;)/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>
          </>
        )
      }
     }
Fpunkt
  • 976
  • 7
  • 13
1
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.

VnoitKumar
  • 1,350
  • 15
  • 29
0

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;
baseem
  • 132
  • 5
  • Thanks for looking into this! I got close to a similar result using fetch but I like your answer too. – cbutler Feb 27 '18 at 22:02
  • sure thing! thanks for posting your solution as well, Im gonna try it out. I should use fetch more often. – baseem Feb 27 '18 at 22:25
0

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}`;
  • This doesn't seem to be an answer to the question. Can you write a full answer that gives instructions on how to achieve the desired result? – Jonathan Rys May 16 '18 at 18:26
0

You can check out this npm package react-translate-with-google-api

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32235955) – sm3sher Jul 16 '22 at 21:00