HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<html>
<body>
<main>
<h1>React</h1>
<div id="root"></div>
</main>
</body>
</html>
: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;
}
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`;
};
Also see: Tab Triggers