Example usage of the React SDK
Code example of how to use the Optimizely Feature Experimentation React SDK to send Decision events, make flag decisions and implement the Track method.
Prerequisites
Before using the client to evaluate flag rules, including A/B tests and flag deliveries, you must complete the following:
Example React SDK implementation
This example walks through the following three key steps:
-
Evaluate a flag with the key
product_sortusing the Decision hook. 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. The Track method ties the purchase back to the A/B test and sends it to Optimizely through the event dispatcher so it shows up on your results page.
import React from 'react';
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 handleClick = () => {
const { optimizely } = props;
optimizely.track('purchased')
};
return <button onClick={handleClick}>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 && <div className="error">{ decision.reasons }</div> }
{ /* If feature is enabled, do something with the Sort Method variable */ }
{ isEnabled && <div>The Sort method is {sortMethod}</div> }
{ /* Show relevant component based on the variation key */ }
{ variationKey === 'control' && <div>Control Component</div> }
{ variationKey === 'treatment' && <div>Treatment Component</div> }
{ /* Show Purchase Button to track Purchase event */ }
<PurchaseButton />
</div>
)
}
function App() {
return (
<OptimizelyProvider optimizely={optimizely} user={{ id: 'user123' }}>
<ProductSort />
</OptimizelyProvider>
);
}
export default App;Updated 18 days ago
