reactjstiktok

Calling TikTok Pixel events in React


I am trying to include a TikTok pixel in an application. According to their docs, I'm supposed to include their base code in the <head> tag and call the corresponding event whenever I'd like it to track, for example: ttq.track('CompleteRegistration') when a registration is complete in the application.

How I do this in a React/Redux application?

For example, we have a HTML.jsx where I can include the pixel script in either the <head> tag (or just before the </body> tag in order prevent page rendering:

<script dangerouslySetInnerHTML={{
    __html: `the-pixel-code-here`, // this sets up the ttq variable
}} />

But in my child components where I want an event to fire, their docs say to call ttq.track('CompleteRegistration') so let's say, I do something like this:

export const completeRegistration = (somePayload) => {
    // do all the things that you need to do to complete a registration
    ...
    const response = server.post('/registration', somePayload)
    if (response.statusCode === 200) {
        ...
        ttq.track('CompleteRegistration')
    } 
    ...
}

export const RegFormSubmitButton = () => {
    return (<button onClick={() => completeRegistration(this.props.somePayload)}>Submit</button>)
}

But instead, I get an error saying:

Cannot find name 'ttq'
'ttq' is not defined

Can anyone help me out?


Solution

  • This kind of libraries generally add a global variable, which can be accessed on window object like window.ttq

    The code snippet can also be added in src/index.js instead of public/index.html (or added to a separate file and imported into index.js file). Note that the script initializing will be relatively late in this case, only after react is initialized.

    Coming to typescript warning, we can extend the Window interface to include ttq property, or simply type cast window like (window as any).ttq wherever you have to use the library.

    (Answered the question to avoid unnecessary attention.)