Overview

This guide shows how to integrate Unlingo with React applications using i18next, one of the most popular internationalization frameworks. You’ll learn how to set up a custom backend that fetches translations from Unlingo and integrates seamlessly with i18next.

Prerequisites

  • React application
  • Basic knowledge of React hooks
  • An Unlingo project with translations

Installation

Install the required dependencies:
npm install i18next react-i18next

Setting Up the Unlingo Backend

Create a custom i18next backend that fetches translations from Unlingo:
class UnlingoBackend {
    constructor() {
        this.type = 'backend';
        // You can add own options if needed
        this.init();
    }

    init() {}

    async read(language, namespace, callback) {
        try {
            const url = new URL('/v1/translations', 'https://api.unlingo.com');
            url.searchParams.set('release', process.env.UNLINGO_RELEASE_TAG);
            url.searchParams.set('namespace', namespace);
            url.searchParams.set('lang', language);

            const response = await fetch(url.toString(), {
                method: 'GET',
                headers: {
                    'x-api-key': process.env.UNLINGO_API_KEY,
                    'Content-Type': 'application/json',
                },
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                return callback(new Error(`HTTP ${response.status}: ${errorData.error || response.statusText}`), null);
            }

            const data = await response.json();
            callback(null, data);
        } catch (error) {
            console.error('Unlingo Backend Error:', error);
            callback(error, null);
        }
    }
}

export default UnlingoBackend;

Configuring i18next

Set up i18next with the Unlingo backend:
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import UnlingoBackend from './unlingo-backend';

i18next.use(UnlingoBackend).use(initReactI18next).init({
    lng: 'en',
    fallbackLng: 'en',
});

export default i18next;

Environment Variables

Add your Unlingo credentials to your environment file:
.env.local
UNLINGO_API_KEY=your_api_key_here
UNLINGO_RELEASE_TAG=1.0.0

Initializing in Your App

Import and initialize i18next in your main App component:
import React, { Suspense } from 'react';
import './i18n'; // Import i18n configuration
import MainApp from './MainApp';

function App() {
    return (
        <Suspense fallback={<div>Loading translations...</div>}>
            <MainApp />
        </Suspense>
    );
}

export default App;

Next Steps