JSPM

  • Created
  • Published
  • Downloads 23
  • Score
    100M100P100Q94693F
  • License ISC

A reusable cookie consent banner component for Google Analytics integration

Package Exports

  • ga-cookie-consent
  • ga-cookie-consent/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ga-cookie-consent) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Cookie Consent Banner for Google Analytics

Installation

Install the package via npm:

npm install ga-cookie-consent

Usage

index.html

You do not need to add the Google Analytics script to your index.html file. The package will automatically add the script when the user gives consent.

ConsentBanner – Basic Usage

Add the consent banner to your application:

import { ConsentBanner } from 'ga-cookie-consent';

function App() {
  return (
    <>
      {/* Your app components */}
      
      {/* Cookie consent banner with your GA4 ID */}
      <ConsentBanner ga4Id="G-XXXXXXXXXX" />
    </>
  );
}

useGAPageTracking – Automatic Page Tracking

Track page views automatically with the useGAPageTracking hook:

import { useGAPageTracking } from 'ga-cookie-consent';
import { Route } from 'react-router-dom';

const AppRoutes = () => {
  // Initialize automatic page tracking
  const gtagId = import.meta.env.VITE_GA_ID;
  useGAPageTracking(gtagId);
  
  return (
    <>
      <Route path="/home" component={HomePage} />
      <Route path="/about" component={AboutPage} />
      {/* Other routes */}
    </>
  );
};

trackEvent – Custom Event Tracking

Track custom events in your components:

import { trackEvent } from 'ga-cookie-consent';

const ProductCard = ({ product }) => {
  const handleClick = () => {
    // Track when a user clicks on a product
    trackEvent("click", "Product", product.name);
    // Other logic...
  };

  return (
    <div onClick={handleClick}>
      <h3>{product.name}</h3>
      <p>{product.description}</p>
    </div>
  );
};

Check if the user has given consent before performing tracking actions:

import { hasUserConsent } from 'ga-cookie-consent';

const AnalyticsComponent = () => {
  const performTracking = () => {
    if (hasUserConsent()) {
      // Perform tracking action
      console.log("Tracking enabled!");
    } else {
      console.log("User hasn't provided consent, skipping tracking");
    }
  };
  
  return (
    <button onClick={performTracking}>Check Tracking Status</button>
  );
};