How to use google translation api with react
Asked Answered
B

6

7

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

Brim answered 27/2, 2018 at 20:11 Comment(3)
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?Heritor
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..Brim
Ahhh maybe I can just use fetch to make a call using an API key..Brim
V
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;
Vastitude answered 27/2, 2018 at 21:52 Comment(2)
Thanks for looking into this! I got close to a similar result using fetch but I like your answer too.Brim
sure thing! thanks for posting your solution as well, Im gonna try it out. I should use fetch more often.Vastitude
B
10

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

Brim answered 27/2, 2018 at 21:48 Comment(3)
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 renderHeritor
key and target inside url lack of an equal sign(=) in order to work properly. Apart from that perfect solutionBitterroot
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 !!Dorthea
M
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>
          </>
        )
      }
     }
Marcus answered 1/2, 2019 at 21:22 Comment(1)
Fpunkt. How can i translate rich text intput like html tag added? My input text is "<p>Hello</p>"Amberambergris
S
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.

Snoopy answered 8/7, 2020 at 3:8 Comment(0)
V
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;
Vastitude answered 27/2, 2018 at 21:52 Comment(2)
Thanks for looking into this! I got close to a similar result using fetch but I like your answer too.Brim
sure thing! thanks for posting your solution as well, Im gonna try it out. I should use fetch more often.Vastitude
V
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}`;
Vortumnus answered 16/5, 2018 at 18:11 Comment(1)
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?Boil
S
0

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

Sort answered 13/7, 2022 at 8:43 Comment(1)
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 ReviewAhlers

© 2022 - 2024 — McMap. All rights reserved.