This package has been deprecated

Author message:

Package is obsolete. Use @olenbetong/ob-react instead.

@olenbetong/translation-hook

1.0.16 • Public • Published

@olenbetong/translation-hook

Hook that can be used to translate text using Googles translation API.

Installation

NPM:

npm i @olenbetong/translation-hook
import { useTranslation } from '@olenbetong/translation-hook';

IIFE and ESM builds are available on unpkg.com. For IIFE, the components are available in the global ReactTranslationHook variable.

<script src="https://unpkg.com/@olenbetong/translation-hook@latest/dist/iife/translation-hook.min.js" type="text/javascript"></script>
<script type="text/javascript">
const { useTranslation } = ReactTranslationHook;
</script>
<script type="module">
import { useTranslation } from "https://unpkg.com/@olenbetong/translation-hook@latest/dist/esm/translation-hook.min.js";
</script>

Usage

The hook returns an object with these properties:

  • error - Error message if the translation failed
  • from - The language code for the detected language
  • isTranslating - Boolean indicating if the translation has started
  • translation - The translated text (blank if translate hasn't run)
  • translate - Function to trigger the translation

This example component displays a button that triggers the translation if the text hasn't been translated yet:

function getLanguage(code) {
  switch (code) {
  case 'en': return af.common.getLocalizedString('english');
  case 'no': return af.common.getLocalizedString('norwegian');
  case 'pl': return af.common.getLocalizedString('polish');
  case 'ru': return af.common.getLocalizedString('russian');
  default: return code;
  }
}

function Comment(props) {
  const { Comment } = props;
  const uiculture = af.userSession.uiculture.substring(0, 2);

  const {
    error,
    from,
    isTranslating,
    translation,
    translate,
  } = useTranslation(Comment, uiculture, 'some-api-key');

  return <div>
    <p>{Comment}</p>
    {!translation &&
      <button className='btn btn-secondary' onClick={translate} disabled={isTranslating}>
        {isTranslating && <i className='fa fa-spin fa-spinner'/>}
        {af.common.getLocalizedString('Translate')}
      </button>
    }
    {translation && <p>
      {translation}<br/>
      <small className='text-muted'>({af.common.getLocalizedString('Automatically translated from')} {getLanguage(from)})</small>
    </p>}
  </div>
}

Browser compatability

This component is compiled to be used with modern browsers. The last few versions of these browsers are supported:

  • Chrome
  • Firefox
  • Edge
  • Safari

Readme

Keywords

Package Sidebar

Install

npm i @olenbetong/translation-hook

Weekly Downloads

0

Version

1.0.16

License

MIT

Unpacked Size

30 kB

Total Files

11

Last publish

Collaborators

  • bjornarvh