The React SDK enables you to use hooks to retrieve the user’s preferences.
Getting Started
1. Install the SDK
Install the SDK with your preferred package manager.
npm install @microapp-io/react
2. Wrap Your App with the Provider
Wrap your application with the UserPreferencesProvider
component.
import { UserPreferencesProvider } from '@microapp-io/react';
function App() {
return (
<UserPreferencesProvider>
<YourApp />
</UserPreferencesProvider>
);
}
For development, you can use the sandbox mode to test different language preferences:
<UserPreferencesProvider sandbox={{ lang: 'pt' }}>
<YourApp />
</UserPreferencesProvider>
The sandbox
prop should only be used for local development. Do not use it in production.
3. Access Language Preferences
Use the useUserPreferences
hook to access the user’s language preference.
import { useUserPreferences } from '@microapp-io/react';
function LanguageDisplay() {
const { lang } = useUserPreferences();
return (
<div>
<p>Current language: {lang}</p>
</div>
);
}
The language preference is controlled by the user through the Microapp platform. Your application should respect this preference and adapt accordingly.
4. Create Translation Files
Store your translations in a separate file to keep them organized and maintainable.
// 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'
}
};
5. Render Localized Content
Use the language preference to display content in the appropriate language.
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>
);
}
6. Localize API Requests (Optional)
When fetching data from an API, you can include the user’s language preference in the request headers.
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);
}
};
// ...
}