Simple React components to automatically translate strings with Google Translate API
npm install react-auto-translate
npm install -S react-auto-translateyarn add react-auto-translate
`Usage
React Auto Translate uses React Context API to pass the translation handler around. Wrap your top component with the component.`jsx
// App.js
import {Translator, Translate} from 'react-auto-translate';return (
cacheProvider={cacheProvider}
from='en'
to='es'
googleApiKey='API_KEY'
>
Welcome!
...
);
`API
$3
- cacheProvider: optional handler to cache the translated strings.
- to: Language to translate to. See full list here.
- from: Language text is provided in. Defaults to en.
- googleApiKey: required Google Cloud Api Key to use for translating.$3
- Fully customizable handler to store the translated text. You can also use this to override and initialize the translations for your app.
- If not provided, it will ping Google for the translation every time the component is rendered.
- Must be an object that conforms to the following type.
`ts
type CacheProvider = {
get: (language: string, key: string) => string | undefined;
set: (language: string, key: string, translation: string) => void;
};// example procider
const cacheProvider = {
get: (language, key) =>
((JSON.parse(localStorage.getItem('translations')) || {})[key] || {})[
language
],
set: (language, key, value) => {
const existing = JSON.parse(localStorage.getItem('translations')) || {
[key]: {},
};
existing[key] = {...existing[key], [language]: value};
localStorage.setItem('translations', JSON.stringify(existing));
},
};
``