DEV Community

Cover image for useTranslator - a React translation hook
Chad Steele
Chad Steele

Posted on

useTranslator - a React translation hook

I just wanted to share a little javascript library I developed to use Google translate API for free. First is the javascript class TranslateApi that you can use independent of react. Next is the useTranslator hook that makes it super convenient in a React component. I'm using spanish here, but you can use any language that google supports. Also, if you have a better API, you can easily substitute it inside the TranslationApi class.

TranslationApi.js

In raw javascript, it's a simple asynchronous function..

   TranslationApi.translate("dog","spanish").then(palabras=>{
      elDog = palabras;
   });
Enter fullscreen mode Exit fullscreen mode

get source TranslationApi.js

useTranslator.js

In your react component, you use it much like useState...

  const [spanish, toSpanish] = useTranslator('spanish');
     ...
  let elDog = toSpanish('dog');
Enter fullscreen mode Exit fullscreen mode

get source useTranslator.js

dogs

¡Hasta luego bebe!

-ChadSteele.com

p.s.
If you like this, you might like this other library
Vocabulary.js

Top comments (0)