The React SDK enables you to use hooks to retrieve the user’s theme preferences.
Getting Started
1. Install the SDK
Install the SDK with your preferred package manager.
npm install @microapp-io/react
yarn add @microapp-io/react
pnpm add @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>{/* Your app code here */}</UserPreferencesProvider>;}
For local development, use the sandbox feature to test different theme preferences:
import { UserPreferencesProvider } from '@microapp-io/react';const options = { theme: "dark",};function App() { return ( <UserPreferencesProvider sandbox={options}> {/* Your app code here */} </UserPreferencesProvider> );}
The sandbox prop should only be used for local development. Make sure to remove it before deploying to production. In production, theme preferences are controlled by the user through the Microapp platform.
3. Access Theme Preferences
Use the useUserPreferences hook to access the user’s theme preference.
The theme preference is controlled by the user through the Microapp platform. Your application should respect this preference and adapt accordingly.
4. Create and Apply Theme Styles
Define your theme styles in separate files and apply them based on the user’s theme preference.
1. For Microapp UI and Tailwind Apps
For Microapp UI and Tailwind CSS apps, we recommend using next-themes to handle theme application:
npm install next-themes
yarn add next-themes
pnpm add next-themes
Configure your Tailwind setup to work with next-themes:
// tailwind.config.jsmodule.exports = { // Note: Tailwind only supports dark mode in version > 2 darkMode: 'selector', // If you're using Tailwind < 3.4.1, use 'class' instead // ...};
Then integrate next-themes with your Microapp preferences:
import { useUserPreferences } from '@microapp-io/react';import { ThemeProvider } from 'next-themes';function App() { const { theme } = useUserPreferences(); const attribute = undefined; // If you're using Tailwind < 3.4.1, use 'class' instead return ( <ThemeProvider forcedTheme={theme} attribute={attribute}> {/* Rest of your app */} </ThemeProvider> );}
Or you can set up a two-way sync to update Microapp when the theme changes locally: