Example usage of the React Native SDK v4+
2 min
Prerequisites
Before using the client to evaluate flag rules, including A/B tests and flag deliveries, you must complete the following:
- Install the React Native SDKInstall the React Native SDK.
- Initialize the React Native SDKInitialize the React Native SDK.
Example React Native SDK implementation
This example walks through the following three key steps:
- Evaluate a flag with the key product_sort using the decide hooksdecide hooks. This also sends a decision eventdecision event to Optimizely to record that the user was exposed to the experiment.
- Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:
- Check the flag's enabled state and read a configuration variable (sort_method) to determine which experience the user gets.
- Check the flag variation directly and run the corresponding control or treatment code.
- Track a conversion event called purchased to measure the experiment's impact. The track event methodtrack event method ties the purchase back to the A/B test and sends it to Optimizely through the event dispatcherevent dispatcher so it shows up on your results pageresults page.
import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import {
createInstance,
createPollingProjectConfigManager,
createBatchEventProcessor,
OptimizelyProvider,
useDecide,
useOptimizelyUserContext,
} from '@optimizely/react-sdk';
const optimizely = createInstance({
projectConfigManager: createPollingProjectConfigManager({
sdkKey: 'YOUR_SDK_KEY', // TODO: Update to your SDK Key
}),
eventProcessor: createBatchEventProcessor(),
});
function PurchaseButton() {
const { userContext } = useOptimizelyUserContext();
const handlePress = () => {
userContext?.trackEvent('purchased');
};
return (
<TouchableOpacity onPress={handlePress}>
<Text>Purchase</Text>
</TouchableOpacity>
);
}
function ProductSort() {
const { decision, isLoading, error } = useDecide('product_sort');
if (isLoading) return <Text>Loading...</Text>;
if (error) return <Text>Error: {error.message}</Text>;
const variationKey = decision.variationKey;
const isEnabled = decision.enabled;
const sortMethod = decision.variables['sort_method'];
return (
<View>
{/* If variation is null, display error */}
{variationKey === null && <Text>{decision.reasons}</Text>}
{/* If feature is enabled, do something with the Sort Method variable */}
{isEnabled && <Text>The Sort method is {sortMethod}</Text>}
{/* Show relevant component based on the variation key */}
{variationKey === 'control' && <Text>Control Component</Text>}
{variationKey === 'treatment' && <Text>Treatment Component</Text>}
{/* Show Purchase Button to track Purchase event */}
<PurchaseButton />
</View>
);
}
function App() {
return (
<OptimizelyProvider client={optimizely} user={{ id: 'user123' }}>
<ProductSort />
</OptimizelyProvider>
);
}
export default App;