Clocale

React.js

This guide walks you through integrating Clocale into your React.js application for seamless internationalization support.


Installation

Adding Dependencies

Install the Clocale React package to get started:

npm install @clocale/react

This library provides all the necessary tools for handling translations in your React.js application, including hooks and providers.


Core Setup

Step 1: Create Locale Management Utilities

Create utilities to handle locale persistence using localStorage. This ensures the user's language preference is remembered across sessions:

// src/utils/locale.ts
const LOCALE_KEY = 'locale';

export const getLocale = (): string => {
  return localStorage.getItem(LOCALE_KEY) || 'en';
};

export const setLocale = (locale: string): void => {
  localStorage.setItem(LOCALE_KEY, locale);
};

Key functions:

  • getLocale() - Retrieves the user's saved locale from localStorage (defaults to 'en')
  • setLocale(locale) - Updates the locale in localStorage when users change their language preference

Step 2: Set Up the Provider

Modify your main.tsx file to wrap your application with the Clocale provider. This makes translations available throughout your entire app:

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { ClocaleProvider } from '@clocale/react';
import App from './App.tsx';
import { getLocale } from './utils/locale';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ClocaleProvider
      type="client"
      locale={getLocale()} // Load saved locale preference
      baseUrl="your-project-integration-url"
      isDev={true} // Set to false for production
    >
      <App />
    </ClocaleProvider>
  </StrictMode>
);

Configuration details:

  • type - Set to 'client' for client-side translation fetching
  • locale - Initial locale loaded from localStorage
  • baseUrl - Your Clocale integration URL from the developer settings (Learn more)
  • isDev - Enable development mode helpers (set to false in production)

Important: Only set isDev={true} in development. Always use isDev={false} in production to disable development features. Learn more


Building a Language Switcher

Creating the Locale Switcher Component

A language switcher is essential for allowing users to view your application in their preferred language. This reusable component allows users to change their language preference.

import { useLocale } from '@clocale/react';
import { setLocale as saveLocale } from '../utils/locale';

const LANGUAGES = [
  { code: 'en', label: 'English' },
  { code: 'fr', label: 'Français' },
  { code: 'es', label: 'Español' },
  { code: 'de', label: 'Deutsch' },
];

export const LocaleSwitcher = () => {
  const { locale, setLocale } = useLocale();

  const handleLocaleChange = (newLocale: string) => {
    // Update the locale in the provider
    setLocale(newLocale);
  };

  return (
    <select
      value={locale}
      onChange={(e) => handleLocaleChange(e.target.value)}
    >
      {LANGUAGES.map((lang) => (
        <option key={lang.code} value={lang.code}>
          {lang.label}
        </option>
      ))}
    </select>
  );
};

Using the Locale Switcher

Add the locale switcher to your layout or navigation component:

import { LocaleSwitcher } from './components/LocaleSwitcher';

export default function Header() {
  return (
    <header>
      <nav>
        <h1>My App</h1>
        <LocaleSwitcher />
      </nav>
    </header>
  );
}

Using Translations

Use the useTranslation hook to access translations in your React components:

import { useTranslation } from "@clocale/react";

const Login = () => {
  // Access translations for the "default" namespace
  const { t } = useTranslation("default"); 
  
  return (
    <div>
      <h2>{t("auth.title")}</h2>
      <p>{t("auth.description")}</p>
      <input 
        type="text" 
        placeholder={t("auth.input.email.placeholder")}
      />
    </div>
  );
}

export default Login;

Quick Reference

Hook/UtilityPurposeUsage
useTranslation('namespace')Access translationsconst { t } = useTranslation('auth')
useLocale()Get/set current localeconst { locale, setLocale } = useLocale()
getLocale()Retrieve saved localeconst locale = getLocale()
setLocale(locale)Save locale preferencesetLocale('fr')

On this page