React: Serving different modules based on Variation

This Article Will Help You:


Overview

Convert can work alongside React using different methods. One of them is to serve different modules depending on the variation that Convert randomly selects for the visitors. 

The advantages and disadvantages of this method are:

  1. You have a lot of flexibility by encapsulating variations in React modules.
  2. You will need to compile your code every time you create a new test.

How to

To enable the above we will need to use the Convert on-page api that will provide us with the ID of the variation randomly selected for your visitor. This selection happens as soon as the Convert script starts running when loaded via the Convert tracking code.

First, we will provide an example of the React container that will return the Variation that has been selected randomly for your visitor:

// convert-abtest-container.js

var ConvertAbTestContainer = React.createClass({

propTypes: {
experimentId: React.PropTypes.string.isRequired,
defaultVariationId: React.PropTypes.string.isRequired,
variations: React.PropTypes.arrayOf(React.PropTypes.shape({
variationId: React.PropTypes.string.isRequired,
component: React.PropTypes.element.isRequired
}))
},

getVariation: function () {
// Make sure you perform appropriate guard checks before using this in production!
var activeExperiments = window.convert.currentData.experiments;
var isExperimentActive = _.contains(activeExperiments, this.props.experimentId);
var variation, variationId;

if (isExperimentActive) {
// Gets the Original/Control id to see if it is in the active experiments.
variationId = Object.keys(window.convert.data.experiments[experimenId].vars)[0];
} else {
variationId = this.props.defaultVariationId;
}

variation = _.findWhere(this.props.variations, { variationId: variationId });
return variation;
},

render: function () {
return this.getVariation();
}

});

 

Next, we have this code example of how the first React container is called and then the corresponding Variation module served:

...

render: function () {
var variations = [
{ variationId: '123456790', component: <FirstVariationComponent/> },
{ variationId: '123456791', component: <SecondVariationComponent/> }
];

return (
<AbTestContainer
experimentId='123456789'
defaultVariationId='123456790'
variations={variations}
/>
);
}

...

 

Please read the Single Page Apps article to learn more on how to implement this type of experiment.