ga-cookie-consent
v1.2.4
Published
A reusable cookie consent banner component for Google Analytics integration
Downloads
41
Maintainers
Readme
Cookie Consent Banner for Google Analytics
Installation
Install the package via npm:
npm install ga-cookie-consentUsage
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>
);
};Checking Consent Status
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>
);
};