Examples
Real-world examples demonstrating how to implement LiveI18n in various React application scenarios.
Complete Application Examples
E-commerce Product Page
A complete product page with internationalized content:
import React, { useState } from 'react';
import { LiveText } from '@livei18n/react-sdk';
function ProductPage({ product }) {
const [selectedSize, setSelectedSize] = useState('');
const [quantity, setQuantity] = useState(1);
return (
<div className="product-page">
{/* Breadcrumb Navigation */}
<nav className="breadcrumb">
<LiveText context="navigation">Home</LiveText> /
<LiveText context="navigation">Products</LiveText> /
<span>{product.name}</span>
</nav>
<div className="product-content">
<div className="product-images">
<img src={product.image} alt={product.name} />
</div>
<div className="product-details">
<h1>{product.name}</h1>
<div className="price">
<LiveText context="product pricing">Price:</LiveText>
<span className="amount">${product.price}</span>
</div>
<div className="description">
<LiveText context="product description" tone="marketing">
{product.description}
</LiveText>
</div>
{/* Size Selection */}
<div className="size-selection">
<label>
<LiveText context="product options">Size:</LiveText>
</label>
<select
value={selectedSize}
onChange={(e) => setSelectedSize(e.target.value)}
>
<option value="">
<LiveText context="form placeholder">Select a size</LiveText>
</option>
{product.sizes.map(size => (
<option key={size} value={size}>{size}</option>
))}
</select>
</div>
{/* Quantity Selection */}
<div className="quantity-selection">
<label>
<LiveText context="product options">Quantity:</LiveText>
</label>
<input
type="number"
min="1"
value={quantity}
onChange={(e) => setQuantity(parseInt(e.target.value))}
/>
</div>
{/* Action Buttons */}
<div className="product-actions">
<button
className="add-to-cart"
disabled={!selectedSize}
>
<LiveText context="shopping action" tone="action">
Add to Cart
</LiveText>
</button>
<button className="buy-now">
<LiveText context="shopping action" tone="urgent">
Buy Now
</LiveText>
</button>
</div>
{/* Product Features */}
<div className="product-features">
<h3>
<LiveText context="product info">Features</LiveText>
</h3>
<ul>
{product.features.map((feature, index) => (
<li key={index}>
<LiveText context="product feature" tone="informational">
{feature}
</LiveText>
</li>
))}
</ul>
</div>
{/* Shipping Info */}
<div className="shipping-info">
<LiveText context="shipping information" tone="helpful">
Free shipping on orders over $50. Delivery in 2-3 business days.
</LiveText>
</div>
</div>
</div>
{/* Reviews Section */}
<ReviewsSection productId={product.id} />
</div>
);
}
function ReviewsSection({ productId }) {
const [reviews] = useState([]); // Fetch reviews here
return (
<section className="reviews">
<h2>
<LiveText context="product reviews">Customer Reviews</LiveText>
</h2>
{reviews.length === 0 ? (
<p>
<LiveText context="empty state" tone="encouraging">
Be the first to review this product!
</LiveText>
</p>
) : (
reviews.map(review => (
<div key={review.id} className="review">
<div className="review-header">
<span className="reviewer-name">{review.author}</span>
<div className="rating">★★★★☆</div>
</div>
<p className="review-text">{review.text}</p>
</div>
))
)}
</section>
);
}
export default ProductPage;
Dashboard Application
A comprehensive dashboard with multiple translated elements:
import React, { useState, useEffect } from 'react';
import { LiveText } from '@livei18n/react-sdk';
function Dashboard() {
const [stats, setStats] = useState(null);
const [timeRange, setTimeRange] = useState('7d');
useEffect(() => {
// Fetch dashboard data
fetchDashboardData(timeRange).then(setStats);
}, [timeRange]);
if (!stats) {
return (
<div className="loading">
<LiveText context="loading state">Loading dashboard...</LiveText>
</div>
);
}
return (
<div className="dashboard">
{/* Header */}
<header className="dashboard-header">
<h1>
<LiveText context="dashboard title">Analytics Dashboard</LiveText>
</h1>
<div className="time-range-selector">
<LiveText context="dashboard controls">Time Range:</LiveText>
<select
value={timeRange}
onChange={(e) => setTimeRange(e.target.value)}
>
<option value="1d">
<LiveText context="time period">Last 24 hours</LiveText>
</option>
<option value="7d">
<LiveText context="time period">Last 7 days</LiveText>
</option>
<option value="30d">
<LiveText context="time period">Last 30 days</LiveText>
</option>
</select>
</div>
</header>
{/* Key Metrics */}
<div className="metrics-grid">
<MetricCard
title={<LiveText context="dashboard metric">Total Users</LiveText>}
value={stats.totalUsers}
change={stats.userGrowth}
icon="👥"
/>
<MetricCard
title={<LiveText context="dashboard metric">Revenue</LiveText>}
value={`$${stats.revenue.toLocaleString()}`}
change={stats.revenueGrowth}
icon="💰"
/>
<MetricCard
title={<LiveText context="dashboard metric">Conversions</LiveText>}
value={stats.conversions}
change={stats.conversionGrowth}
icon="📈"
/>
<MetricCard
title={<LiveText context="dashboard metric">Bounce Rate</LiveText>}
value={`${stats.bounceRate}%`}
change={stats.bounceRateChange}
icon="📊"
/>
</div>
{/* Charts Section */}
<div className="charts-section">
<div className="chart-container">
<h2>
<LiveText context="dashboard chart">Traffic Overview</LiveText>
</h2>
<TrafficChart data={stats.trafficData} />
</div>
<div className="chart-container">
<h2>
<LiveText context="dashboard chart">Top Pages</LiveText>
</h2>
<TopPagesTable pages={stats.topPages} />
</div>
</div>
{/* Recent Activity */}
<ActivityFeed activities={stats.recentActivity} />
</div>
);
}
function MetricCard({ title, value, change, icon }) {
const isPositive = change > 0;
return (
<div className="metric-card">
<div className="metric-icon">{icon}</div>
<div className="metric-content">
<h3>{title}</h3>
<div className="metric-value">{value}</div>
<div className={`metric-change ${isPositive ? 'positive' : 'negative'}`}>
<span>{isPositive ? '↗' : '↘'} {Math.abs(change)}%</span>
<LiveText context="dashboard change" tone="neutral">
vs previous period
</LiveText>
</div>
</div>
</div>
);
}
function ActivityFeed({ activities }) {
return (
<section className="activity-feed">
<h2>
<LiveText context="dashboard section">Recent Activity</LiveText>
</h2>
{activities.length === 0 ? (
<p>
<LiveText context="empty state">No recent activity</LiveText>
</p>
) : (
<ul className="activity-list">
{activities.map(activity => (
<li key={activity.id} className="activity-item">
<div className="activity-content">
<LiveText
context="activity description"
tone="informational"
>
{activity.description}
</LiveText>
</div>
<time className="activity-time">
{formatTime(activity.timestamp)}
</time>
</li>
))}
</ul>
)}
</section>
);
}
// Helper functions
function fetchDashboardData(timeRange) {
// Mock data - replace with actual API call
return Promise.resolve({
totalUsers: 12543,
userGrowth: 12.5,
revenue: 45678,
revenueGrowth: 8.3,
conversions: 234,
conversionGrowth: -2.1,
bounceRate: 34.2,
bounceRateChange: -5.4,
trafficData: [],
topPages: [],
recentActivity: []
});
}
function formatTime(timestamp) {
// Format timestamp - replace with your preferred formatting
return new Date(timestamp).toLocaleString();
}
Multi-step Form
A complex form with validation and internationalized error messages:
import React, { useState } from 'react';
import { LiveText } from '@livei18n/react-sdk';
function MultiStepForm() {
const [currentStep, setCurrentStep] = useState(1);
const [formData, setFormData] = useState({
personalInfo: {},
contactInfo: {},
preferences: {}
});
const [errors, setErrors] = useState({});
const totalSteps = 3;
const updateField = (section, field, value) => {
setFormData(prev => ({
...prev,
[section]: {
...prev[section],
[field]: value
}
}));
// Clear error when user starts typing
if (errors[`${section}.${field}`]) {
setErrors(prev => {
const newErrors = { ...prev };
delete newErrors[`${section}.${field}`];
return newErrors;
});
}
};
const validateStep = (step) => {
const newErrors = {};
if (step === 1) {
if (!formData.personalInfo.firstName) {
newErrors['personalInfo.firstName'] = 'First name is required';
}
if (!formData.personalInfo.lastName) {
newErrors['personalInfo.lastName'] = 'Last name is required';
}
if (!formData.personalInfo.dateOfBirth) {
newErrors['personalInfo.dateOfBirth'] = 'Date of birth is required';
}
} else if (step === 2) {
if (!formData.contactInfo.email) {
newErrors['contactInfo.email'] = 'Email is required';
}
if (!formData.contactInfo.phone) {
newErrors['contactInfo.phone'] = 'Phone number is required';
}
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const nextStep = () => {
if (validateStep(currentStep)) {
setCurrentStep(prev => Math.min(prev + 1, totalSteps));
}
};
const prevStep = () => {
setCurrentStep(prev => Math.max(prev - 1, 1));
};
const handleSubmit = () => {
if (validateStep(currentStep)) {
console.log('Form submitted:', formData);
// Handle form submission
}
};
return (
<div className="multi-step-form">
{/* Progress Indicator */}
<div className="progress-indicator">
<h2>
<LiveText context="form progress">
Step {currentStep} of {totalSteps}
</LiveText>
</h2>
<div className="progress-bar">
<div
className="progress-fill"
style={{ width: `${(currentStep / totalSteps) * 100}%` }}
/>
</div>
</div>
{/* Form Steps */}
{currentStep === 1 && (
<PersonalInfoStep
data={formData.personalInfo}
errors={errors}
onChange={(field, value) => updateField('personalInfo', field, value)}
/>
)}
{currentStep === 2 && (
<ContactInfoStep
data={formData.contactInfo}
errors={errors}
onChange={(field, value) => updateField('contactInfo', field, value)}
/>
)}
{currentStep === 3 && (
<PreferencesStep
data={formData.preferences}
onChange={(field, value) => updateField('preferences', field, value)}
/>
)}
{/* Navigation Buttons */}
<div className="form-navigation">
{currentStep > 1 && (
<button type="button" onClick={prevStep} className="btn-secondary">
<LiveText context="form navigation">Previous</LiveText>
</button>
)}
{currentStep < totalSteps ? (
<button type="button" onClick={nextStep} className="btn-primary">
<LiveText context="form navigation">Next</LiveText>
</button>
) : (
<button type="button" onClick={handleSubmit} className="btn-primary">
<LiveText context="form submission" tone="action">
Complete Registration
</LiveText>
</button>
)}
</div>
</div>
);
}
function PersonalInfoStep({ data, errors, onChange }) {
return (
<div className="form-step">
<h3>
<LiveText context="form section">Personal Information</LiveText>
</h3>
<FormField
label={<LiveText context="form label">First Name</LiveText>}
error={errors['personalInfo.firstName']}
required
>
<input
type="text"
value={data.firstName || ''}
onChange={(e) => onChange('firstName', e.target.value)}
placeholder="Enter your first name"
/>
</FormField>
<FormField
label={<LiveText context="form label">Last Name</LiveText>}
error={errors['personalInfo.lastName']}
required
>
<input
type="text"
value={data.lastName || ''}
onChange={(e) => onChange('lastName', e.target.value)}
placeholder="Enter your last name"
/>
</FormField>
<FormField
label={<LiveText context="form label">Date of Birth</LiveText>}
error={errors['personalInfo.dateOfBirth']}
required
>
<input
type="date"
value={data.dateOfBirth || ''}
onChange={(e) => onChange('dateOfBirth', e.target.value)}
/>
</FormField>
</div>
);
}
function ContactInfoStep({ data, errors, onChange }) {
return (
<div className="form-step">
<h3>
<LiveText context="form section">Contact Information</LiveText>
</h3>
<FormField
label={<LiveText context="form label">Email Address</LiveText>}
error={errors['contactInfo.email']}
required
>
<input
type="email"
value={data.email || ''}
onChange={(e) => onChange('email', e.target.value)}
placeholder="Enter your email"
/>
</FormField>
<FormField
label={<LiveText context="form label">Phone Number</LiveText>}
error={errors['contactInfo.phone']}
required
>
<input
type="tel"
value={data.phone || ''}
onChange={(e) => onChange('phone', e.target.value)}
placeholder="Enter your phone number"
/>
</FormField>
<FormField
label={<LiveText context="form label">Address (Optional)</LiveText>}
>
<textarea
value={data.address || ''}
onChange={(e) => onChange('address', e.target.value)}
placeholder="Enter your address"
rows="3"
/>
</FormField>
</div>
);
}
function PreferencesStep({ data, onChange }) {
return (
<div className="form-step">
<h3>
<LiveText context="form section">Preferences</LiveText>
</h3>
<FormField
label={<LiveText context="form label">Communication Preferences</LiveText>}
>
<div className="checkbox-group">
<label>
<input
type="checkbox"
checked={data.emailUpdates || false}
onChange={(e) => onChange('emailUpdates', e.target.checked)}
/>
<LiveText context="form option">Email updates</LiveText>
</label>
<label>
<input
type="checkbox"
checked={data.smsUpdates || false}
onChange={(e) => onChange('smsUpdates', e.target.checked)}
/>
<LiveText context="form option">SMS notifications</LiveText>
</label>
</div>
</FormField>
<FormField
label={<LiveText context="form label">Preferred Language</LiveText>}
>
<select
value={data.language || ''}
onChange={(e) => onChange('language', e.target.value)}
>
<option value="">
<LiveText context="form placeholder">Select a language</LiveText>
</option>
<option value="en">English</option>
<option value="es">Español</option>
<option value="fr">Français</option>
<option value="de">Deutsch</option>
</select>
</FormField>
</div>
);
}
function FormField({ label, error, required, children }) {
return (
<div className="form-field">
<label className="form-label">
{label}
{required && <span className="required">*</span>}
</label>
{children}
{error && (
<div className="form-error">
<LiveText context="validation error" tone="helpful">
{error}
</LiveText>
</div>
)}
</div>
);
}
export default MultiStepForm;
Testing Examples
Component Testing
import { render, screen } from '@testing-library/react';
import { LiveText } from '@livei18n/react-sdk';
// Mock the SDK for testing
jest.mock('@livei18n/react-sdk', () => ({
LiveText: ({ children, ...props }) => (
<span data-testid="live-text" {...props}>
{children}
</span>
),
initializeLiveI18n: jest.fn()
}));
test('renders product page with translations', () => {
const mockProduct = {
name: 'Test Product',
price: 29.99,
description: 'A great product',
sizes: ['S', 'M', 'L'],
features: ['Feature 1', 'Feature 2']
};
render(<ProductPage product={mockProduct} />);
// Verify translated elements are present
expect(screen.getByText('Home')).toBeInTheDocument();
expect(screen.getByText('Add to Cart')).toBeInTheDocument();
expect(screen.getByText('Price:')).toBeInTheDocument();
});
Integration Testing
import { initializeLiveI18n } from '@livei18n/react-sdk';
// Test the demo functionality
describe('Demo Integration', () => {
beforeAll(() => {
initializeLiveI18n({
apiKey: process.env.REACT_APP_LIVEI18N_API_KEY,
customerId: process.env.REACT_APP_LIVEI18N_CUSTOMER_ID,
debug: true
});
});
test('translations work with real API', async () => {
// Test implementation would go here
// This would typically test against a staging environment
});
});
Live Demo
Try all these examples live at react-demo.livei18n.com:
- Enter your API keys
- Test different examples
- Try various languages
- See real-time translations
Next Steps
Now that you've seen real-world examples:
- Review best practices - Optimization tips
- Learn caching strategies - Performance tuning
- Try the demo - Test your own implementations
- Contribute examples - Share your own implementations
Getting Help
Questions about implementing these examples?
- Check our GitHub repository for the complete source code
- Join our Discord community for discussions
- Contact support for implementation assistance
- Review our API documentation for advanced features