React, i18next and translations in sleekdocs

Translating a React application can be streamlined using i18next, a powerful internationalization framework. In this guide, we’ll show you how to integrate i18next with your React project and manage translations efficiently using Sleekdocs Translate.

Installing nvm, Node.js and React

# Install nvm from https://github.com/nvm-sh/nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash
# Install Node 20
nvm i 20

# Create React application
npx create-react-app react-i18n --template typescript
cd react-i18n
# Install i18next packages
npm install react-i18next i18next i18next-http-backend
# Start development server
npm start

Point browser to http://localhost:3000 to access application.

Adding i18n support

Now create a new file i18n.ts next to App.tsx with this content:

import i18next from "i18next";
import Backend from "i18next-http-backend";
import {initReactI18next} from "react-i18next";

await i18next
    .use(Backend)
    .use(initReactI18next)
    .init({
        fallbackLng: 'en',
        backend: {
            loadPath: 'https://cdn.sleekdocs.com/c10602cc-0657-4839-89c8-bb9116898b86/dev/{{lng}}.json'
        }
    });

Then we edit the default App.tsx to look like this:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import './i18n';
import {changeLanguage} from "i18next";
import {useTranslation} from 'react-i18next';

function App() {
    const {t} = useTranslation();

    return (
        <div className="App">
            <header className="App-header">
                <img src={logo} className="App-logo" alt="logo"/>
                <p>
                    Edit <code>src/App.tsx</code> and save to reloads.
                </p>
                <p>
                    {t('HELLO_WORLD')}
                </p>
                <p>
                    <button onClick={() => changeLanguage('en')}>English</button>
                    <button onClick={() => changeLanguage('sv')}>Swedish</button>
                    <button onClick={() => changeLanguage('dummy')}>Dummy (fallback to 'en')</button>
                </p>
                <a
                    className="App-link"
                    href="https://reactjs.org"
                    target="_blank"
                    rel="noopener noreferrer"
                >
                    Learn React
                </a>
            </header>
        </div>
    );
}

export default App;

Conclusion

Integrating i18next with React and managing translations through Sleekdocs Translate simplifies the process of making your application available in multiple languages. By following these steps, you can enhance your app’s accessibility and reach a broader audience.