Advanced Features
Explore advanced features and customization options of the LiveI18n React SDK for complex use cases.
Custom Configuration
SDK Configuration Options
import { initializeLiveI18n } from '@livei18n/react-sdk';
initializeLiveI18n({
apiKey: process.env.REACT_APP_LIVEI18N_API_KEY,
customerId: process.env.REACT_APP_LIVEI18N_CUSTOMER_ID,
// Custom API endpoint (optional)
endpoint: 'https://api.livei18n.com',
// Cache configuration
cache: {
maxSize: 1000, // Increase cache size
ttlHours: 2 // Extend cache TTL
},
// Default language fallback
defaultLanguage: 'en-US',
// Debug mode for development
debug: process.env.NODE_ENV === 'development',
// Request timeout (milliseconds)
timeout: 10000,
// Custom headers
headers: {
'X-App-Version': '1.0.0'
}
});
Advanced Component Usage
Conditional Translation
function ConditionalTranslation({ shouldTranslate, text }) {
if (shouldTranslate) {
return <LiveText>{text}</LiveText>;
}
return <span>{text}</span>;
}
Dynamic Language Switching
import { useState } from 'react';
function LanguageSwitcher() {
const [currentLanguage, setCurrentLanguage] = useState('auto');
const languages = [
{ code: 'auto', name: 'Auto-detect' },
{ code: 'es-ES', name: 'Español' },
{ code: 'fr-FR', name: 'Français' },
{ code: 'de-DE', name: 'Deutsch' }
];
return (
<div>
<select
value={currentLanguage}
onChange={(e) => setCurrentLanguage(e.target.value)}
>
{languages.map(lang => (
<option key={lang.code} value={lang.code}>
{lang.name}
</option>
))}
</select>
<p>
<LiveText
language={currentLanguage === 'auto' ? undefined : currentLanguage}
>
This text will be translated to the selected language
</LiveText>
</p>
</div>
);
}
Higher-Order Component
Create a HOC for consistent translation configuration:
function withTranslation(Component, defaultProps = {}) {
return function TranslatedComponent(props) {
const translationProps = {
context: 'general',
tone: 'neutral',
...defaultProps,
...props
};
return <Component {...translationProps} />;
};
}
// Usage
const TranslatedButton = withTranslation('button', {
context: 'ui button',
tone: 'action'
});
function MyComponent() {
return (
<TranslatedButton>
<LiveText>Click me</LiveText>
</TranslatedButton>
);
}
Custom Hooks
useTranslation Hook
Create a custom hook for programmatic translations:
import { useState, useEffect } from 'react';
import { translate } from '@livei18n/react-sdk';
function useTranslation() {
const [isLoading, setIsLoading] = useState(false);
const translateText = async (text, options = {}) => {
setIsLoading(true);
try {
const result = await translate(text, options);
return result;
} catch (error) {
console.error('Translation failed:', error);
return text; // Fallback
} finally {
setIsLoading(false);
}
};
return { translateText, isLoading };
}
// Usage
function DynamicTranslation() {
const { translateText, isLoading } = useTranslation();
const [translatedText, setTranslatedText] = useState('');
useEffect(() => {
translateText('Hello, dynamic world!', {
language: 'es-ES',
context: 'greeting'
}).then(setTranslatedText);
}, []);
if (isLoading) return <div>Translating...</div>;
return <div>{translatedText}</div>;
}
useLanguage Hook
Manage language state across components:
import { useState, createContext, useContext } from 'react';
const LanguageContext = createContext();
export function LanguageProvider({ children }) {
const [language, setLanguage] = useState('auto');
return (
<LanguageContext.Provider value={{ language, setLanguage }}>
{children}
</LanguageContext.Provider>
);
}
export function useLanguage() {
const context = useContext(LanguageContext);
if (!context) {
throw new Error('useLanguage must be used within LanguageProvider');
}
return context;
}
// Usage
function LanguageAwareComponent() {
const { language } = useLanguage();
return (
<LiveText language={language === 'auto' ? undefined : language}>
This respects the global language setting
</LiveText>
);
}
Performance Optimization
Memoization
Use React.memo for components with stable translations:
import React, { memo } from 'react';
const StaticTranslation = memo(function StaticTranslation({ text, context }) {
return (
<LiveText context={context}>
{text}
</LiveText>
);
});
// Only re-renders if text or context changes
function OptimizedComponent() {
return (
<StaticTranslation
text="Static welcome message"
context="hero section"
/>
);
}
Lazy Loading
Defer translation of off-screen content:
import { useState, useEffect, useRef } from 'react';
function LazyTranslation({ children, ...props }) {
const [isVisible, setIsVisible] = useState(false);
const ref = useRef();
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.disconnect();
}
},
{ threshold: 0.1 }
);
if (ref.current) {
observer.observe(ref.current);
}
return () => observer.disconnect();
}, []);
return (
<div ref={ref}>
{isVisible ? (
<LiveText {...props}>{children}</LiveText>
) : (
<span>{children}</span>
)}
</div>
);
}
Batch Translation
Group multiple translations into single requests:
function BatchTranslationExample() {
const texts = [
'Welcome to our platform',
'Get started in minutes',
'Join thousands of users'
];
return (
<div>
{texts.map((text, index) => (
<LiveText
key={index}
context="hero section"
tone="marketing"
>
{text}
</LiveText>
))}
</div>
);
}
Error Handling
Custom Error Boundaries
Handle translation errors gracefully:
import React from 'react';
class TranslationErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Translation error:', error, errorInfo);
// Log to error reporting service
}
render() {
if (this.state.hasError) {
return (
<span>
{this.props.fallback || this.props.children}
</span>
);
}
return this.props.children;
}
}
// Usage
function SafeTranslation({ text }) {
return (
<TranslationErrorBoundary fallback={text}>
<LiveText>{text}</LiveText>
</TranslationErrorBoundary>
);
}
Retry Logic
Implement automatic retry for failed translations:
function RetryTranslation({ children, maxRetries = 3, ...props }) {
const [retryCount, setRetryCount] = useState(0);
const [error, setError] = useState(null);
const handleError = (error) => {
if (retryCount < maxRetries) {
setRetryCount(prev => prev + 1);
// Trigger retry after delay
setTimeout(() => {
setError(null);
}, 1000 * Math.pow(2, retryCount)); // Exponential backoff
} else {
setError(error);
}
};
if (error) {
return <span>{children}</span>; // Fallback
}
return (
<LiveText
{...props}
onError={handleError}
>
{children}
</LiveText>
);
}
Integration Patterns
State Management Integration
Redux Integration
// actions/translation.js
export const setLanguage = (language) => ({
type: 'SET_LANGUAGE',
payload: language
});
// reducers/translation.js
const initialState = {
currentLanguage: 'auto'
};
export default function translationReducer(state = initialState, action) {
switch (action.type) {
case 'SET_LANGUAGE':
return {
...state,
currentLanguage: action.payload
};
default:
return state;
}
}
// components/TranslatedText.jsx
import { useSelector } from 'react-redux';
function ReduxTranslatedText({ children, ...props }) {
const currentLanguage = useSelector(state => state.translation.currentLanguage);
return (
<LiveText
language={currentLanguage === 'auto' ? undefined : currentLanguage}
{...props}
>
{children}
</LiveText>
);
}
Context API Integration
const TranslationContext = createContext();
function TranslationProvider({ children }) {
const [settings, setSettings] = useState({
language: 'auto',
tone: 'neutral',
context: 'general'
});
return (
<TranslationContext.Provider value={{ settings, setSettings }}>
{children}
</TranslationContext.Provider>
);
}
function ContextAwareLiveText({ children, overrides = {} }) {
const { settings } = useContext(TranslationContext);
const finalProps = {
...settings,
...overrides
};
return (
<LiveText {...finalProps}>
{children}
</LiveText>
);
}
Form Integration
function InternationalizedForm() {
const [formData, setFormData] = useState({});
const [errors, setErrors] = useState({});
const validateField = (name, value) => {
// Your validation logic
return value ? null : 'This field is required';
};
return (
<form>
<div>
<label>
<LiveText context="form label">Full Name</LiveText>
</label>
<input
type="text"
onChange={(e) => {
const error = validateField('name', e.target.value);
setErrors(prev => ({ ...prev, name: error }));
}}
/>
{errors.name && (
<div className="error">
<LiveText context="validation error" tone="helpful">
{errors.name}
</LiveText>
</div>
)}
</div>
</form>
);
}
Testing Advanced Features
Mock Advanced Configurations
// test-utils/translation-mocks.js
export const mockTranslationConfig = {
apiKey: 'test-key',
customerId: 'test-customer',
debug: true,
cache: { maxSize: 100, ttlHours: 0.1 }
};
export const setupTranslationMocks = () => {
jest.mock('@livei18n/react-sdk', () => ({
initializeLiveI18n: jest.fn(),
LiveText: ({ children, ...props }) => (
<span data-testid="live-text" {...props}>
{children}
</span>
)
}));
};
Integration Tests
import { render, screen } from '@testing-library/react';
import { setupTranslationMocks } from './test-utils/translation-mocks';
setupTranslationMocks();
test('advanced translation features work correctly', () => {
render(
<LanguageProvider>
<ContextAwareLiveText overrides={{ tone: 'friendly' }}>
Hello, world!
</ContextAwareLiveText>
</LanguageProvider>
);
expect(screen.getByTestId('live-text')).toBeInTheDocument();
});
Debugging
Debug Mode
Enable comprehensive logging:
initializeLiveI18n({
// ... other config
debug: true
});
// This will log:
// - Cache hits/misses
// - API requests/responses
// - Performance metrics
// - Error details
Performance Monitoring
function PerformanceMonitor() {
useEffect(() => {
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
if (entry.name.includes('livei18n')) {
console.log('Translation performance:', {
name: entry.name,
duration: entry.duration,
startTime: entry.startTime
});
}
});
});
observer.observe({ entryTypes: ['measure'] });
return () => observer.disconnect();
}, []);
return null;
}
Next Steps
You've now learned the advanced features of the React SDK:
- See real examples - Complete implementations
- Learn best practices - Optimization strategies
- Try the demo - Test advanced features
- Explore caching strategies - Performance optimization
Support
For advanced use cases or custom implementations:
- Check our GitHub repository for latest updates
- Join our Discord community for discussions
- Contact enterprise support for custom solutions
- Review our API documentation for direct integration