Quick Start - React

Quick start guide for setting up translations in a React application.


React Configuration

Installation

Install using Yarn:

yarn add @resourge/translations

or NPM:

npm install @resourge/translations --save

Configuration

To set up translations for React, follow these steps:

  1. Install the necessary dependencies:
yarn add @resourge/react-translations

or

npm install @resourge/react-translations --save
  1. Import the required functions and types from @resourge/react-translations and use the SetupReactTranslations function:
import { SetupReactTranslations, languageLocalStorage, navigatorLanguageDetector } from '@resourge/react-translations';

const { TranslationInstance, useTranslation } = SetupReactTranslations({
  langs: ['pt', 'en', 'es'],
  defaultLanguage: 'pt',
  plugins: [
    navigatorLanguageDetector({
      onLanguage: (language) => language.split('-')[0]
    }),
    languageLocalStorage()
  ],
  translations: {
    global: {
      hello: { pt: 'Olá', en: 'Hello', es: 'Ola' }
    }
  }
});

export { TranslationInstance, useTranslation };

Usage in React Component

To use the translation functionalities in your React component:

  1. Import the TranslationProvider from @resourge/react-translations.

  2. Define the TranslationInstance in your component.

  3. Wrap your application’s root component with the TranslationProvider, passing TranslationInstance as a prop.

<React.Suspense>
  <TranslationProvider TranslationInstance={TranslationInstance}>
    <RouterView />
  </TranslationProvider>
</React.Suspense>

Replace TranslationInstance with your actual implementation.

Example

These components demonstrate how to use the T object to access translations for the hello key in the global namespace. The buttons trigger the changeLanguage function to switch between languages.

import React from 'react';
import { useTranslation } from './shared/Translations'; //  Replace with your actual implementation

const MyComponent = () => {
  const { T, changeLanguage } = useTranslation();

  return (
    <div>
      <div>{T.global.hello}</div>
      <button onClick={() => changeLanguage('en')}>Change Language to English</button>
      <button onClick={() => changeLanguage('pt')}>Mudar Idioma para Português</button>
      <button onClick={() => changeLanguage('es')}>Cambiar Idioma a Español</button>
    </div>
  );
}

export default MyComponent;