Hi @SetoSeng,
I build and interact with React Apps that integrate with Klaviyo too.
One of the big questions here is whether you’re dealing with an SPA or a server-based app.
Regardless, you could certainly use that snippet, and I’d recommend loading it before you load your app. I have my third party scripts (like user analytics platforms) loaded before loading the app itself.
Here’s an example of my code for an SPA showing how I initialize (slightly edited).
init().then(({ store }) => {
const MOUNT_NODE = document.getElementById(APP_ELEMENT_ID);
ReactDOM.render(
<Provider store={store}>
<AppRouter />
</Provider>,
MOUNT_NODE
);
afterRender(store);
});
The `init` function loads all my third party data (and yes, I literally load a JS file as abstract as the snippet you posted for my third party integrations).
However, just so you know, I don’t actually use that Klaviyo object. I wrote a pretty simple Klaviyo API layer, and I call my own functions when I want to track things to Klaviyo. Please note that this API layer is only for the “public” endpoints from Klaviyo. It does not use the API Secret, just the API Public key.
Here’s an example…
export const track = (event, customerProps, eventProps) => {
const data = {
token: ,
event,
customer_properties: customerProps,
properties: eventProps
};
return axios.post(TRACK_ENDPOINT, new URLSearchParams({ data: JSON.stringify(data) }));
};
I use this API layer across multiple projects (including some server side calls, some Next.js apps, and SPAs).
So the takeaway is there are a lot of ways of working with Klaviyo in React. Let me know if you have any more questions.
Cheers,
Kevin.