reactjsgoogle-translate

How to use google translation api with react


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


Solution

  • 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;