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:
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:
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:
Configuration details:
type- Set to'client'for client-side translation fetchinglocale- Initial locale loaded from localStoragebaseUrl- Your Clocale integration URL from the developer settings (Learn more)isDev- Enable development mode helpers (set tofalsein production)
Important: Only set
isDev={true}in development. Always useisDev={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.
Using the Locale Switcher
Add the locale switcher to your layout or navigation component:
Using Translations
Use the useTranslation hook to access translations in your React components:
Quick Reference
| Hook/Utility | Purpose | Usage |
|---|---|---|
useTranslation('namespace') | Access translations | const { t } = useTranslation('auth') |
useLocale() | Get/set current locale | const { locale, setLocale } = useLocale() |
getLocale() | Retrieve saved locale | const locale = getLocale() |
setLocale(locale) | Save locale preference | setLocale('fr') |