Clocale

React.js

Prerequisites

Before starting, ensure you have:

  • An existing React.js project
  • A plan for which languages your application will support

Installing Dependencies

First, add the Clocale package to your project:

npm install @clocale/react

This library provides the core functionality for handling translations in your React.js application.

Setting Up the Provider

Modify the main.tsx file to handle dynamic loading of translations based on the user's selected locale:

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

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ClocaleProvider
      type="client"
      locale="en" // default locale for your project
      baseUrl="your-project-integration-url"
      isDev={true} // set value to false for production environment
    >
      <App />
    </ClocaleProvider>
  </StrictMode>
);

You can connect to the localization service for dynamic content translation using the baseUrl from your project's developer settings. This URL is essential for establishing a connection between your application and the Clocale service. Learn more

⚠️ Important: Only set isDev=true in development. Never enable this in production. Learn more

Localizing Components

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

const Login = () => {
  // Access translations for the "default" namespace
  const { t } = useTranslation("default.auth"); 

  // `t` returns the translated string
  return (
    <div>
      <h2>{t("title")}</h2>
      <p>{t("description")}</p>
      <input 
          type="text" 
          placeholder={t("input.login.placeholder")}
      />
    </div>
  );
}

On this page