Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>

<body>
  <main>
    <h1>React</h1>
    <div id="root"></div>
  </main>
</body>

</html>
              
            
!

CSS

              
                :root {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 24px;
  font-weight: 400;

  color-scheme: light dark;
  color: rgba(255, 255, 255, 0.87);
  background-color: #242424;

  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-text-size-adjust: 100%;
}

body {
  margin: 0 auto;
  display: flex;
  justify-content: center;
  place-items: center;
  color: #ffffff;
  height: 100%;
  width: 100%;
}

h1 {
  text-align: center;
  font-size: 3.2em;
  line-height: 1.1;
}

.card-container {
  width: 100%;
  justify-content: center;
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
}

.card {
  text-align: center;
  flex: 0 0 200px;
  margin: 10px;
}

.data-layer {
  padding: 10px;
  text-align: center;
  width: 100%;
}

button {
  border-radius: 8px;
  border: 1px solid transparent;
  padding: 0.6em 1.2em;
  font-size: 1em;
  font-weight: 500;
  font-family: inherit;
  background-color: #1a1a1a;
  cursor: pointer;
  transition: border-color 0.25s;
}

table,
th,
td {
  min-width: 50%;
  max-width: 100%;
  text-align: center;
  color: white;
  padding: 5px;
  border: 1px solid black;
}

button:hover {
  border-color: #646cff;
}

button:focus,
button:focus-visible {
  outline: 4px auto -webkit-focus-ring-color;
}

              
            
!

JS

              
                const { useState, useEffect, useCallback, Fragment } = React;
const { createRoot } = ReactDOM;
import {
  buildConfig,
  trackAnalyticsEvent,
  analyticsPlatform
} from "https://cdn.skypack.dev/react-marketing-tools@0.2.7";
// TagManager is optional but a recomended way to add Google Tag Manager to your appp.
// import TagManager from "https://cdn.skypack.dev/react-gtm-module@2.0.11";

function App() {
  const [count, setCount] = useState({
    register: 0,
    login: 0
  });
  const [windowDataLayer, setWindowDataLayer] = useState([]);

  const handleButtonClick = useCallback(
    async (event) => {
      event.preventDefault();
      // id will be either "register" or "login"
      // normally this function will exist in different files
      // we are using the "id" to consolidate the code a little
      const { id } = event.currentTarget;

      const countActual = count[id] + 1;
      setCount({ ...count, [id]: countActual });
      setWindowDataLayer([]);

      const eventNameInfo = {
        // If this is not passed in the event name will be a combination of actionPrefix & globalAppEvent
        // I_REGISTER or I_LOGIN
        eventName: `${id} account`,
        actionPrefix: "I", // INTERACTION | J: JOURNEY
        globalAppEvent: id.toUpperCase(),
        ...(id.includes("login") && {
          previousGlobalAppEvent: "UNAUTHENTICATED"
        })
      };

      const trackingData = {
        data: {
          count: countActual,
          email: "yeahnah@gmail.com"
        },
        eventNameInfo,
        analyticsType: analyticsPlatform.DATALAYER_PUSH,
        consoleLogData: {
          // These will show the data being added ti the dataLayer in the console
          showGlobalVars: true,
          showJourneyPropsPayload: true,
          showUserProps: true
        },
        dataLayerCheck: false, // When true, you will not see duplicate entries into the dataLayer
        // If you are sending identifiable user data to Google it should be hashed.
        // This data can be hashed one way "meaning you dont need to unhash it with the key" by adding the user data keys which will be in the data object below  e.g. userDataToHashKeyArray: ['email']
        // If you need to match your data up or group it you can do it by the hash string
        userDataToHashKeyArray: null
      };

      await trackAnalyticsEvent(trackingData);
    },
    [count]
  );

  const showDataLayer = () => {
    setWindowDataLayer(window.dataLayer);
  };

  return (
    <div className="App">
      <h1>React Marketing Tools</h1>
      <div className="card-container">
        <div className="card">
          <button id="register" onClick={handleButtonClick}>
            Register
          </button>
          <h2>Register count {count.register}</h2>
        </div>
        <div className="card">
          <button id="login" onClick={handleButtonClick}>
            Login
          </button>
          <h2>Login count {count.login}</h2>
        </div>

        <div className="data-layer">
          <hr />
          <button id="dataLayer" onClick={showDataLayer}>
            Show dataLayer
          </button>
        </div>
        <table>
          <thead>
            <tr>
              <th>Event</th>
              <th>globalVars</th>
              <th>values</th>
              <th>journeyProps</th>
              <th>values</th>
              <th>userProps</th>
              <th>values</th>
            </tr>
          </thead>
          {windowDataLayer.map((item, index) => {
            const key = `${item.journeyProps.HIT_TIMESTAMP}-${index}`;

            return (
              <tbody key={key}>
                <tr>
                  <td>{item.event}</td>
                </tr>
                <tr>
                  <td></td>
                  <td>app:</td>
                  <td>{item.globalVars.app}</td>
                  <td>COUNT:</td>
                  <td>{item.journeyProps.COUNT}</td>
                  <td>client_id:</td>
                  <td>{item.userProps.client_id}</td>
                </tr>
                <tr>
                  <td></td>
                  <td>device_browser:</td>
                  <td>{item.globalVars.device_browser}</td>
                  <td>HIT_TIMESTAMP:</td>
                  <td>{item.journeyProps.HIT_TIMESTAMP}</td>
                  <td>email:</td>
                  <td>{item.userProps.email}</td>
                </tr>
                <tr>
                  <td></td>
                  <td>device_category:</td>
                  <td>{item.globalVars.device_category}</td>
                </tr>
                <tr>
                  <td></td>
                  <td>device_os:</td>
                  <td>{item.globalVars.device_os}</td>
                </tr>
              </tbody>
            );
          })}
        </table>
      </div>
    </div>
  );
}

/* Example of how tokens could be added to config.
  const TOKENS: Tokens = { // all TOKENS are optional
    IP_INFO_TOKEN: 'SOME_TOKEN', // if withDeviceInfo is true you must supply this token.
    // if analyticsType = analyticsPlatform.GOOGLE the below tokens must be supplied.
    GA4_PUBLIC_API_SECRET: 'SOME_TOKEN',
    GA4_PUBLIC_MEASUREMENT_ID: 'SOME_TOKEN',
  }
*/

/*
  These are the keys for the values you want to include in your user data
  these must be included for any user data to be collected by analytics.
*/
const includeUserKeys = [];

const analyticsConfig = {
  appName: "my-awesome-app",
  appSessionCookieName: "CodePen",
  eventActionPrefix: {},
  globalEventActionList: {
    // this will extend the default values of globalEventActionList
    LOGIN: "LOGIN",
    REGISTER: "REGISTER",
    UNAUTHENTICATED: "UNAUTHENTICATED",
    AUTHENTICATED: "AUTHENTICATED"
  },
  includeUserKeys,
  showMissingUserAttributesInConsole: true,
  // TOKENS,
  withDeviceInfo: true,
  withServerLocationInfo: false
};

/**
 * @type {Object} buildConfig -> options: all attributes of the options object must have a value, other than withDeviceInfo.
 * @property {string} appName: the name of your app this value must be passed in.
 * @property {string} appSessionCookieName This is used to get the cookie from storage based on a key you use, the value from the cookie will be used in "client_id:"
 * @property {Object} eventActionPrefix: is a { key: 'value' } object that allows you to extend "analyticsEventActionPrefixList" object with custom eventActionPrefix. To see the build in list call the function showMeBuildInEventActionPrefixList().
 * @property {Object} globalEventActionList: is a { key: 'value' } object that allows you to extend "analyticsGlobalEventActionList" object with custom eventActionNames. To see the build in list call the function showMeBuildInGlobalEventActionList().
 * @property {Array} includeUserKeys: is an array of strings that represent keys from your user data that you want to whitelist, user data you wan to hash.
 * @property {Boolean} showMissingUserAttributesInConsole a boolean condition to show or hide "user" attributes that are not included in the "includeUserKeys" array, by console logging in dev tools.
 * @property {Object} TOKENS: is a { key: 'value' } object that includes the following keys, IP_INFO_TOKEN, GA4_PUBLIC_API_SECRET, GA4_PUBLIC_MEASUREMENT_ID, depending on if you need these features enabled.
 * @property {Boolean} withDeviceInfo: if you want device information added to "globalVars" set this to true false by default.
 * @property {Boolean} withServerLocationInfo: if you want server information added to "journeyProps" set this to true false by default.
 */
buildConfig(analyticsConfig);

// const tagManagerArgs = {
//   gtmId: "",
//   dataLayerName: "dataLayer",
//   auth: "",
//   preview: ""
// };

function Main() {
  useEffect(function initiateGoogleTagManager() {
    createSessionCookie(analyticsConfig.appSessionCookieName, 70);

    // TagManager.initialize(tagManagerArgs);
  }, []);

  return (
    <>
      <App />
    </>
  );
}

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<Main />);

/*
  In this case the cookie doesn't work on codepen, but it will work in your app 👍
*/
const createSessionCookie = (name, timeToExpire) => {
  const maxAge = timeToExpire * 60 * 60 * 24 * 365; // e.g. Sat, 05 Feb 54287 13:42:17 GMT aka 365 years
  const value = "some-random-uuid";

  document.cookie = `${name}=${value};max-age=${maxAge};SameSite=Strict;Secure`;
};

              
            
!
999px

Console