Use Google Optimize in React web for A/B Testing

I’ll explain how to create an experiment in the Google Optimize (GO) panel to get a simple boolean flag in our JavaScript code, specifically using Reactjs, to display the original version of our web, or the experiment.

I won’t focus on the creation of…


This content originally appeared on DEV Community and was authored by Axel Navarro

I'll explain how to create an experiment in the Google Optimize (GO) panel to get a simple boolean flag in our JavaScript code, specifically using Reactjs, to display the original version of our web, or the experiment.

I won't focus on the creation of experiments or specific configurations. This post will be centered on how to connect GO with JavaScript code.

Introduction

I needed to integrate Google Optimize to do an A/B testing in a project I'm working on. I've found that GO was made for end users so that they can make little changes (text, CSS styles, etc.) in the website without needing a developer.

But I couldn't find a good guide about how to receive a bool flag in the frontend to develop a basic if in JavaScript.

The Optimize panel

Creating an experiment

First, we should create an A/B test experiment using the Google Optimize panel. Make a click to the Create experiment button. 🧪

The create experience button

Give a name to the experiment and select the A/B test option.

Select the experiment type

When you link the experiment to a Google Analytics (GA) account the experiment receives an Experiment ID.

The experiment ID

🧠 The developer will use this ID to read the flag in the JavaScript code. The experiment name is not used in the JavaScript side.

Make sure you assign an objective to the experiment.

The objectives of the given experiment

Now, you can start the experiment. 🧫

Assigning an activation event

Review the Activation event setting, because you can't use the experiment as a flag in the JavaScript code until that event is fired.

Experiment settings section

You can leave the activation event as page load to let the experiment ready when the page loads.

Evaluate experiment on page load event

Or, you can use a custom event that will activate the experiment.

Evaluate experiment on custom event

Using in JavaScript

Installation

Setup the GO SDK via Google Tag Manager (GTM) or adding the script tag to download it directly.

Reading the flag value

The google_optimize object will be available as a global variable at the window level:

const variant = window.google_optimize.get('<experiment_id>');

If the get function returns undefined that means the experiment is not available for this page. Maybe it is misconfigured, or it doesn't apply for this page, or the experiment ID is not correct.

switch (value) {
  case '0':
    // Code for visitors in the original.
    break;
  case '1':
    // Code for visitors in the first variant.
    break;
  case '2':
    // Code for visitors in another variant.
    break;
  default:
    // Code when the experiment has finished or misconfigured.
}

Dispatching the activation event

If the experiment requires a custom event to activate you should dispatch it

let variant;
if (window.dataLayer) {
  await window.dataLayer.push({event: 'optimize.activate'});
}
const intervalId = setInterval(() => {
  if (window.google_optimize !== undefined) {
    variant = window.google_optimize.get('<experiment_id>');
    clearInterval(intervalId);
  }
}, 500);

We don't know when google_optimize is going to be be available on the window, we should use setInterval to read the variant when the experiment it's available.

React integration

Now we can preset a useful hook for React:

const useExperiment = (experimentId) => {
  const [variant, setVariant] = useState();
  useEffect(() => {
    (async () => {
      if (window.dataLayer) {
        await window.dataLayer.push({ event: 'optimize.activate' })
      }
      const intervalId = setInterval(() => {
        if (window.google_optimize !== undefined) {
          // Set the variant to the state.
          setVariant(
            window.google_optimize.get(experimentId)
          );
          clearInterval(intervalId);
        }
      }, 100);
    })();
  })
  return variant;
}

const MyComponent = () => {
  const variant = useExperiment(YOUR_EXPERIMENT_ID_GOES_HERE);
  // here you can apply your conditional.
  return (
    <div>...</div>
  );
}

Conclusion

Now, you know how to build experiments that send the name of the variant to the frontend and how to read that value in JavaScript code using the Experiment ID to apply the required conditionals to display the correct variant in our web sites.

Additionally, we have a simple React hook to plug in to the React components and build your own variant-verse. 🦸


This content originally appeared on DEV Community and was authored by Axel Navarro


Print Share Comment Cite Upload Translate Updates
APA

Axel Navarro | Sciencx (2021-10-25T11:55:57+00:00) Use Google Optimize in React web for A/B Testing. Retrieved from https://www.scien.cx/2021/10/25/use-google-optimize-in-react-web-for-a-b-testing/

MLA
" » Use Google Optimize in React web for A/B Testing." Axel Navarro | Sciencx - Monday October 25, 2021, https://www.scien.cx/2021/10/25/use-google-optimize-in-react-web-for-a-b-testing/
HARVARD
Axel Navarro | Sciencx Monday October 25, 2021 » Use Google Optimize in React web for A/B Testing., viewed ,<https://www.scien.cx/2021/10/25/use-google-optimize-in-react-web-for-a-b-testing/>
VANCOUVER
Axel Navarro | Sciencx - » Use Google Optimize in React web for A/B Testing. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/25/use-google-optimize-in-react-web-for-a-b-testing/
CHICAGO
" » Use Google Optimize in React web for A/B Testing." Axel Navarro | Sciencx - Accessed . https://www.scien.cx/2021/10/25/use-google-optimize-in-react-web-for-a-b-testing/
IEEE
" » Use Google Optimize in React web for A/B Testing." Axel Navarro | Sciencx [Online]. Available: https://www.scien.cx/2021/10/25/use-google-optimize-in-react-web-for-a-b-testing/. [Accessed: ]
rf:citation
» Use Google Optimize in React web for A/B Testing | Axel Navarro | Sciencx | https://www.scien.cx/2021/10/25/use-google-optimize-in-react-web-for-a-b-testing/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.