Example usage of the React Native SDK
A brief code example of how to use the Optimizely React Native SDK to evaluate feature flags, activate A/B tests, or feature tests.
After installing the React Native SDK, import the Optimizely library, get your project's datafile, and create a client. Use the client to evaluate flag rules like A/B tests and flag deliveries.
This example walks through the following three key steps:
-
Evaluate a flag with the key
product_sortusing theuseDecisionhook. This also sends a decision 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.
- Check the flag's enabled state and read a configuration variable (
-
Track a conversion event called
purchasedto measure the experiment's impact. Thetrackmethod ties the purchase back to the A/B test and sends it to Optimizely so it displays on your Experiment Results page.
import React from 'react';
import {
Button,
Text,
} from 'react-native';
import {
createInstance,
OptimizelyProvider,
useDecision,
withOptimizely,
} from '@optimizely/react-sdk';
const optimizely = createInstance({
sdkKey: '<Your_SDK_Key>', // TODO: Update to your SDK Key
})
function Button(props) {
const handlePress = () => {
const { optimizely } = props;
optimizely.track('purchased')
};
return <Button onPress={handlePress}>Purchase</Button>;
}
const PurchaseButton = withOptimizely(Button)
function ProductSort() {
const [ decision ] = useDecision('product_sort');
const variationKey = decision.variationKey;
const isEnabled = decision.enabled;
const sortMethod = decision.variables['sort_method'];
return (
<div>
{ /* If variation is null, display error */ }
{ variationKey === null && <Text style={styles.error}>{ 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 />
</div>
)
}
function App() {
return (
<OptimizelyProvider optimizely={optimizely} user={{ id: 'user123' }}>
<ProductSort />
</OptimizelyProvider>
);
}
export default App;Updated 14 days ago
