React SDK Integration
The ConfigBee React SDK provides a seamless way to integrate feature flags and dynamic configurations into your React applications. It offers React-specific hooks and components that make it easy to manage feature flags in a React-friendly way.
Installation
Install the ConfigBee React SDK using npm or yarn:
npm install configbee-reactyarn add configbee-reactSetup
Provider Setup
Create a ConfigBee provider component to wrap your application:
"use client"import React from 'react';import { CbWrapper } from 'configbee-react';
const ConfigbeeProvider = ({ children }: { children: React.ReactNode}) => { return ( <CbWrapper accountId="YOUR_ACCOUNT_ID" projectId="YOUR_PROJECT_ID" environmentId="YOUR_ENVIRONMENT_ID" > {children} </CbWrapper> );};
export default ConfigbeeProvider;Replace "YOUR_ACCOUNT_ID", "YOUR_PROJECT_ID", and "YOUR_ENVIRONMENT_ID" with your actual ConfigBee credentials.
Integration with Your Application
Wrap your application with the ConfigBee provider:
// src/app/layout.tsx or App.jsximport React from 'react';import ConfigbeeProvider from '../providers/configbee-provider';
function Layout({ children }: { children: React.ReactNode}) { return ( <html lang="en"> <body> <ConfigbeeProvider> {children} </ConfigbeeProvider> </body> </html> );}
export default Layout;Available Hooks
Status Hooks
Monitor the current state of ConfigBee configuration loading and targeting:
import { useCbStatus, useCbTargetingStatus } from 'configbee-react';
// In your componentconst status = useCbStatus(); // Returns: "LOADING", "ACTIVE", "ERROR"const targetingStatus = useCbTargetingStatus(); // Returns targeting statusStatus Values:
"LOADING": Configuration is being fetched"ACTIVE": Configuration is loaded and ready"ERROR": An error occurred during loading
Configuration Hooks
ConfigBee React SDK provides specialized hooks for each configuration type:
import { useCbFlags, useCbNumbers, useCbTexts, useCbJsons} from 'configbee-react';
// In your component with TypeScriptconst { newFeature, betaAccess } = useCbFlags() as { newFeature?: boolean; betaAccess?: boolean;};
const { maxItems, retryLimit } = useCbNumbers() as { maxItems?: number; retryLimit?: number;};
const { welcomeMessage, errorText } = useCbTexts() as { welcomeMessage?: string; errorText?: string;};
const { appConfig, userPrefs } = useCbJsons() as { appConfig?: { theme: string; locale: string }; userPrefs?: any;};Available Hooks:
useCbFlags(): Fetches boolean feature flagsuseCbNumbers(): Fetches numerical configuration valuesuseCbTexts(): Fetches text-based configurationsuseCbJsons(): Fetches JSON configurations
Operations Hook
The operations hook provides functions to manage targeting properties:
import { useCbOperations } from 'configbee-react';
// In your componentconst cbOps = useCbOperations();
// Set targeting propertiescbOps.setTargetProperties({ userId: "user123", plan: "premium"});
// Clear targeting propertiescbOps.unsetTargetProperties();Available Operation Functions:
setTargetProperties(props): Set or update target properties for personalized configurationsunsetTargetProperties(): Clear all target properties
Targeting
ConfigBee allows you to define target properties to tailor configurations based on specific criteria. You can set target properties using two methods:
Method 1: Using Operation Functions
Use the useCbOperations() hook to dynamically set or clear targeting properties based on user actions:
import React from 'react';import { useCbStatus, useCbTargetingStatus, useCbOperations } from 'configbee-react';
const MyComponent = () => { const cbStatus = useCbStatus(); const cbTargetingStatus = useCbTargetingStatus(); const cbOps = useCbOperations();
const userLogin = ({ userId, userName }: { userId: string; userName: string }) => { if (userId) { cbOps.setTargetProperties({ userId: userId, userName: userName }); } else { cbOps.unsetTargetProperties(); } };
return ( // Your component JSX );};
export default MyComponent;Method 2: Passing Target Properties to CbWrapper
You can also pass target properties directly to the CbWrapper component:
"use client"import React from 'react';import { CbWrapper } from 'configbee-react';
const ConfigbeeProvider = ({ children }: { children: React.ReactNode}) => { const userId = myStorage.userId; const userName = myStorage.userName;
return ( <CbWrapper accountId="YOUR_ACCOUNT_ID" projectId="YOUR_PROJECT_ID" environmentId="YOUR_ENVIRONMENT_ID" targetProperties={{ userId: userId, userName: userName }} > {children} </CbWrapper> );};
export default ConfigbeeProvider;Usage Examples
Feature Flag Based Rendering
import React from 'react';import { useCbStatus, useCbFlags } from 'configbee-react';
const FeatureComponent = () => { const status = useCbStatus(); const { newFeature } = useCbFlags() as { newFeature?: boolean };
if (status !== "ACTIVE") { return <div>Loading...</div>; }
return ( <div> {newFeature ? ( <div>New Feature UI</div> ) : ( <div>Original Feature UI</div> )} </div> );};
export default FeatureComponent;Using Multiple Configuration Types
import React from 'react';import { useCbStatus, useCbFlags, useCbNumbers, useCbTexts, useCbJsons} from 'configbee-react';
const ProductPage = () => { const status = useCbStatus(); const { showReviews } = useCbFlags() as { showReviews?: boolean }; const { itemsPerPage } = useCbNumbers() as { itemsPerPage?: number }; const { productHeader } = useCbTexts() as { productHeader?: string }; const { featureConfig } = useCbJsons() as { featureConfig?: any };
if (status !== "ACTIVE") { return <div>Loading configurations...</div>; }
return ( <div> <h1>{productHeader}</h1> <ProductList itemsPerPage={itemsPerPage} /> {showReviews && <ReviewSection config={featureConfig} />} </div> );};User Targeting Example
import React, { useEffect } from 'react';import { useCbOperations, useCbFlags } from 'configbee-react';
const UserFeatures = ({ user }: { user: any }) => { const cbOps = useCbOperations(); const { premiumFeature, betaFeature } = useCbFlags() as { premiumFeature?: boolean; betaFeature?: boolean; };
useEffect(() => { if (user) { // Set user targeting properties when user logs in cbOps.setTargetProperties({ userId: user.id, userType: user.type, region: user.region, subscriptionTier: user.subscriptionTier }); } else { // Clear targeting when user logs out cbOps.unsetTargetProperties(); } }, [user, cbOps]);
return ( <div> {premiumFeature && <PremiumFeature />} {betaFeature && <BetaFeature />} </div> );};Complete Next.js Page Example
This example demonstrates using all configuration types in a single component:
import React from 'react';import { useCbStatus, useCbFlags, useCbNumbers, useCbJsons, useCbTexts,} from 'configbee-react';
const TestPage = () => { const cbStatus = useCbStatus(); const { isPublished } = useCbFlags() as { isPublished?: boolean }; const { followersCount } = useCbNumbers() as { followersCount?: number }; const { displayName } = useCbTexts() as { displayName?: string }; const { forceUpdate } = useCbJsons() as { forceUpdate?: { required_version: string; is_force_update: boolean }; };
if (cbStatus !== "ACTIVE") { return <div>Loading...</div>; }
return ( <> <h1>Test Page</h1> <p>ConfigBee Status: {cbStatus}</p>
<div> {isPublished === true ? ( <p>Content is published</p> ) : ( <p>Content is not yet published</p> )} </div>
<p>Display Name: {displayName}</p> <p>Followers Count: {followersCount}</p>
<div> <h3>Force Update Configuration:</h3> <p>Required Version: {forceUpdate?.required_version}</p> <p>Force Update: {forceUpdate?.is_force_update ? "Yes" : "No"}</p> </div> </> );};
export default TestPage;Full Application Example (Dashboard)
import React from 'react';import { useCbStatus, useCbFlags, useCbNumbers, useCbTexts, useCbJsons,} from 'configbee-react';
const Dashboard = () => { const status = useCbStatus(); const { newDashboard, showAnalytics } = useCbFlags() as { newDashboard?: boolean; showAnalytics?: boolean; }; const { widgetCount } = useCbNumbers() as { widgetCount?: number }; const { welcomeHeading } = useCbTexts() as { welcomeHeading?: string }; const { dashboardConfig } = useCbJsons() as { dashboardConfig?: any };
if (status !== "ACTIVE") { return <div className="loading">Loading dashboard configurations...</div>; }
return ( <div className="dashboard"> <h1>{welcomeHeading}</h1>
{newDashboard ? ( <NewDashboardLayout widgetCount={widgetCount} config={dashboardConfig} /> ) : ( <LegacyDashboardLayout /> )}
{showAnalytics && <AnalyticsPanel />} </div> );};
export default Dashboard;Best Practices
-
Centralize Provider Configuration: Keep your ConfigBee configuration in a single provider file for easier maintenance and updates.
-
Always Handle Loading States: Check the status before accessing configuration values to prevent undefined errors:
if (status !== "ACTIVE") {return <div>Loading...</div>;} -
Use TypeScript for Type Safety: Add type definitions to your hooks usage for better autocompletion and error detection:
const { featureFlag } = useCbFlags() as { featureFlag?: boolean }; -
Provide Default Values: Consider how your app should behave before configurations are loaded or if they fail to load.
-
Manage Target Properties Lifecycle: Set target properties on user login and clear them on logout to ensure proper personalization.
-
Persist Important Properties: Remember that target properties persist across page loads, so only set them when necessary.
-
Test Both Enabled and Disabled States: Always test your feature flags in both states to ensure proper functionality.