The Guardian's AB Testing Library for React
Getting Started
- Install the package and its peer dependencies with your manager of choice.
e.g.
pnpm add @guardian/ab-react @guardian/ab-core preact
- Initialise the AB Class in your project
- Consume the API in your App or
in your Components
Note Read more on the @guardian/ab-core docs
How it works
- Define the AB test: Each AB test and their variants are defined in code
with configuration such as audience size & offset and impression & success
listeners etc
- Initialise the library: The AB Test library is initialised with
configuration values such as a user's MVT ID, an array of the above defined
A/B tests etc
- Use the AB Test API: The intialisation returns an API that can be used to
check if the current user is in a variant of a test along with a variety of
other API methods
Initialising
Initialise the config options with the ABProvider
import { render } from 'react-dom';
import { ABProvider } from '@guardian/ab-react';
render(
<ABProvider
arrayOfTestObjects={tests}
abTestSwitches={{
...{ abAbTestTest: true },
...CAPI.config.switches,
}}
pageIsSensitive={CAPI.config.isSensitive}
mvtMaxValue={1_000_000}
mvtId={mvtId}
ophanRecord={ophanRecordFunc}
>
<App CAPI={CAPI} NAV={NAV} />
</ABProvider>,
);
Consuming in App
import { useAB } from '@guardian/ab-react';
const ABTestAPI = useAB();
useEffect(() => {
const allRunnableTests = ABTestAPI.allRunnableTests(tests);
ABTestAPI.registerImpressionEvents(allRunnableTests);
ABTestAPI.registerCompleteEvents(allRunnableTests);
}, [ABTestAPI]);
Consuming in Components
import { useAB } from '@guardian/ab-react';
const ABTestAPI = useAB();
const abTestDataAttr =
(ABTestAPI.isUserInVariant('AbTestTest', 'control') && 'ab-test-control') ||
(ABTestAPI.isUserInVariant('AbTestTest', 'variant') && 'ab-test-variant') ||
'ab-test-not-in-test';
const runnableTest = ABTestAPI.runnableTest(abTestTest);
const variantFromRunnable =
(runnableTest && runnableTest.variantToRun.id) || 'not-runnable';
<div
data-ab-user-in-variant={abTestDataAttr}
data-ab-runnable-test={variantFromRunnable}
>
AB Test
</div>;