React Client-Side Setup
This guide covers client-side React integration using the useAutoTranslate
hook for interactive applications.
Prerequisites
npm install react-autolocalise
1. Initialize the SDK
Wrap your application with the TranslationProvider
:
import { TranslationProvider } from "react-autolocalise";
const App = () => {
const config = {
apiKey: "your-api-key",
sourceLocale: "en", // Your app's original language
targetLocale: "es", // Language to translate to
// cacheTTL: 24, // Cache validity in hours (optional, defaults to 24)
};
return (
<TranslationProvider config={config}>
<YourApp />
</TranslationProvider>
);
};
2. Basic Translation
Use the useAutoTranslate
hook in your components:
import { useAutoTranslate } from "react-autolocalise";
const MyComponent = () => {
const { t } = useAutoTranslate();
return (
<div>
<h1>{t("Welcome to our app!")}</h1>
<p>{t("This text will be automatically translated")}</p>
<button>{t("Click me")}</button>
</div>
);
};
3. Advanced Features
Dynamic Content with Variables
import { useAutoTranslate } from "react-autolocalise";
const UserGreeting = ({ userName, messageCount }) => {
const { t } = useAutoTranslate();
return (
<div>
<h2>{t("Welcome, {{1}}!").replace("{{1}}", userName)}</h2>
<p>
{t("You have {{1}} new messages").replace(
"{{1}}",
messageCount.toString()
)}
</p>
</div>
);
};
Nested Text Formatting
For complex formatting that needs to be preserved during translation:
import React from "react";
import { FormattedText } from "react-autolocalise";
const FormattedComponent = () => {
return (
<div>
<FormattedText>
<p>
Hello, we <span style={{ color: "red" }}>want</span> you to be{" "}
<strong style={{ fontWeight: "bold" }}>happy</strong>!
</p>
</FormattedText>
<FormattedText persist={false}>
<div>
This is <em>dynamic content</em> that won't be stored
</div>
</FormattedText>
</div>
);
};
Non-Persisted Translations
For dynamic content that shouldn't be stored in the dashboard:
const DynamicContent = ({ userGeneratedText }) => {
const { t } = useAutoTranslate();
return (
<div>
{/* This will be stored and manageable in dashboard */}
<h3>{t("User Generated Content:")}</h3>
{/* This won't be stored (persist: false) */}
<p>{t(userGeneratedText, false)}</p>
</div>
);
};
4. Configuration Options
TranslationConfig
interface TranslationConfig {
apiKey: string; // Your AutoLocalise API key
sourceLocale: string; // Source language of your content
targetLocale: string; // Target language for translation
cacheTTL?: number; // Cache validity in hours (default: 24)
}
5. Getting User Locale
Browser Detection
// Get the primary locale
const browserLocale = navigator.language; // e.g., 'en-US'
// Get all preferred locales
const preferredLocales = navigator.languages; // e.g., ['en-US', 'en']
// Extract just the language code
const languageCode = browserLocale.split("-")[0]; // e.g., 'en'
URL-based Locale
import { useEffect, useState } from "react";
const useLocaleFromUrl = () => {
const [locale, setLocale] = useState("en");
useEffect(() => {
const pathLocale = window.location.pathname.split("/")[1];
if (pathLocale && pathLocale.length === 2) {
setLocale(pathLocale);
}
}, []);
return locale;
};
6. Best Practices
Translation Management
- Use descriptive text: Write clear, contextual source text
- Avoid technical jargon: Unless necessary for your audience
- Consider text expansion: Some languages require 30-50% more space
- Test with long translations: German and Finnish can be very long
7. Integration with State Management
With Redux
import { useSelector, useDispatch } from "react-redux";
import { TranslationProvider } from "react-autolocalise";
const AppWithRedux = () => {
const locale = useSelector((state) => state.app.locale);
const config = {
apiKey: "your-api-key",
sourceLocale: "en",
targetLocale: locale,
};
return (
<TranslationProvider config={config}>
<App />
</TranslationProvider>
);
};
With Context
import { createContext, useContext, useState } from "react";
import { TranslationProvider } from "react-autolocalise";
const LocaleContext = createContext();
export const LocaleProvider = ({ children }) => {
const [locale, setLocale] = useState("en");
const config = {
apiKey: "your-api-key",
sourceLocale: "en",
targetLocale: locale,
};
return (
<LocaleContext.Provider value={{ locale, setLocale }}>
<TranslationProvider config={config}>{children}</TranslationProvider>
</LocaleContext.Provider>
);
};
export const useLocale = () => useContext(LocaleContext);
Next Steps
- Combine with Next.js SSR for full-stack applications
- Learn about Mobile development for React Native
- Explore API Reference for advanced features