Microapp Localization for React Apps
npm install @microapp-io/react
UserPreferencesProvider
import { UserPreferencesProvider } from '@microapp-io/react'; function App() { return ( <UserPreferencesProvider> <YourApp /> </UserPreferencesProvider> ); }
<UserPreferencesProvider sandbox={{ lang: 'pt' }}> <YourApp /> </UserPreferencesProvider>
sandbox
useUserPreferences
import { useUserPreferences } from '@microapp-io/react'; function LanguageDisplay() { const { lang } = useUserPreferences(); return ( <div> <p>Current language: {lang}</p> </div> ); }
// translations.ts export const translations = { 'en': { greeting: 'Hello', welcome: 'Welcome to our app', description: 'This is a sample application' }, 'es': { greeting: 'Hola', welcome: 'Bienvenido a nuestra aplicación', description: 'Esta es una aplicación de muestra' }, 'pt': { greeting: 'Olá', welcome: 'Bem-vindo ao nosso aplicativo', description: 'Este é um aplicativo de exemplo' } };
import { useUserPreferences } from '@microapp-io/react'; import { translations } from './translations'; function LocalizedContent() { const { lang } = useUserPreferences(); // Default to English if the user's language isn't supported const content = translations[lang] || translations.en; return ( <div> <h1>{content.greeting}</h1> <h2>{content.welcome}</h2> <p>{content.description}</p> </div> ); }
import { useUserPreferences } from '@microapp-io/react'; function DataFetcher() { const { lang } = useUserPreferences(); const fetchLocalizedData = async () => { try { const response = await fetch('https://api.example.com/content', { headers: { // Include the user's language preference in the request headers 'Accept-Language': lang } }); const data = await response.json(); return data; } catch (error) { console.error('Error fetching localized data:', error); } }; // ... }
Was this page helpful?