This app showcases a lightweight approach to implementing A/B tests on a React app.
- Fork this repository to create a copy on your GitHub account.
- Clone the
my-react-apprepository from your GitHub account to create a local copy on your computer. - In the terminal, from within the
my-react-appdirectory, runnpm run start - Your browser should automatically open this React app
- In
index.htmlis a script tag at the top of theheadtag. This simulates a client's script tag to their testing tool (ie Optimizely, Maxymiser, etc) - When this script tag is run, it simulates a
v1test environment - v0 shows all text in the
headerelement in a dark gray color - v1 changes the COLORS
h1tag color to white - In order to simulate a
contorlorv0environment, just comment out the script tag
NOTE: In this app, state change can be observed by clicking the circle button to change the page's background color
- In the
Button.jscomponent code are 2 React lifecycle functionscomponentDidMount&componentDidUpdate// runs on page load/reload componentDidMount() { } // runs immediately after component is updated/state changes componentDidUpdate() { }
- Within these functions are a few lines of code that call a global function called
testingToolHook()// Calling this function in each of the lifecycle functions will cause it be run on page load and any time the state changes componentDidMount() { if (window.testingToolHook) { window.testingToolHook(); } } componentDidUpdate() { if (window.testingToolHook) { window.testingToolHook(); } }
- We then define the
testingToolHook()function in thetest-code.jsfile and place all test code within the function- This file simulates the variation JavaScript that would be put into a testing tool
// test-code.js window.testingToolHook = function() { // Test code here }; // Because we are putting all our test code inside this testingToolHook() function, it will run and persist through all page loads and state changes
This app was bootstrapped with Create React App.
The approach of using React's lifecycle methods in an A/B testing environment was originally posted on Hackernoon.