DEV Community

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

Posted on

1 1

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more