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.
Once you've installed the SDK, import the Optimizely library into your code, get your Optimizely project's datafile, and instantiate a client. Then, you can use the client to evaluate flag rules, including A/B tests and flag deliveries.
This example demonstrates the basic usage of each of these concepts:
-
Evaluate a flag with the key
product_sort
using the Decision hook. As a side effect, the Decision hook also sends a decision event to Optimizely to record that the current user has been exposed to the experiment. -
Conditionally execute your feature code. You have a couple of options:
- Fetch the flag enabled state, then check a configuration variable on the flag called
sort_method
. The SDK evaluates your flag rules and determines what flag variation the user is in, and therefore which sort method variable they should see. - Fetch on the flag variation, then run 'control' or 'treatment' code.
- Use event tracking to track an event called
purchased
. This conversion event measures the impact of an experiment. Using the Track method, the purchase is automatically attributed back to the running A/B test for which Optimizely made a decision, and the SDK sends a network request to Optimizely using the customizable event dispatcher so Optimizely can count it in your 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 Sorth 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 11 months ago