简体   繁体   中英

Where should analytics script be put in a React app?

Barion Pixel requires to put in code in my React app. When I put it in App.js or index.js , it raise an error. Do you have any idea where to put it? In index.html inhas no effect. Strange.

https://docs.barion.com/Implementing_the_Base_Barion_Pixel

<script>
        // Create BP element on the window
        window["bp"] = window["bp"] || function () {
            (window["bp"].q = window["bp"].q || []).push(arguments);
        };
        window["bp"].l = 1 * new Date();

        // Insert a script tag on the top of the head to load bp.js
        scriptElement = document.createElement("script");
        firstScript = document.getElementsByTagName("script")[0];
        scriptElement.async = true;
        scriptElement.src = 'https://pixel.barion.com/bp.js';
        firstScript.parentNode.insertBefore(scriptElement, firstScript);

        // Send init event
        bp('init', 'addBarionPixelId', 'BP-0000000000-00');
    </script>

I just show how error looks like:

在此处输入图像描述

You can try using dangerouslySetInnerHTML :

    <script
      dangerouslySetInnerHTML={{
        __html: `
        // Create BP element on the window
        window["bp"] = window["bp"] || function () {
            (window["bp"].q = window["bp"].q || []).push(arguments);
        };
        window["bp"].l = 1 * new Date();

        // Insert a script tag on the top of the head to load bp.js
        scriptElement = document.createElement("script");
        firstScript = document.getElementsByTagName("script")[0];
        scriptElement.async = true;
        scriptElement.src = 'https://pixel.barion.com/bp.js';
        firstScript.parentNode.insertBefore(scriptElement, firstScript);

        // Send init event
        bp('init', 'addBarionPixelId', 'BP-0000000000-00');`
      }}
    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM