### Install Dependencies and Run Vite Playground Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Installs project dependencies and starts the Vite development server for the playground. Ensure you are at the repository root for the initial install. ```bash pnpm install cd playground pnpm install pnpm dev ``` -------------------------------- ### Install Dependencies and Run Next.js Playground Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Installs project dependencies and starts the Next.js (App Router) development server for the playground. Ensure you are at the repository root for the initial install. ```bash pnpm install cd ../playground-next pnpm install pnpm dev ``` -------------------------------- ### Basic CookieManager Setup Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Demonstrates the basic setup of the CookieManager component with custom translations and an onManage callback. ```jsx import { CookieManager } from "react-cookie-manager"; function App() { return ( console.log("Cookie preferences:", preferences) } > ); } ``` -------------------------------- ### DetailedCookieConsent Example Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/types.md An example demonstrating the structure of DetailedCookieConsent, showing consent status and timestamps for Analytics, Social, and Advertising categories. ```typescript { Analytics: { consented: true, timestamp: "2024-01-15T10:30:00.000Z" }, Social: { consented: false, timestamp: "2024-01-15T10:30:00.000Z" }, Advertising: { consented: false, timestamp: "2024-01-15T10:30:00.000Z" } } ``` -------------------------------- ### E-commerce Setup with Conversion Tracking Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/google-consent-mode.md Configure `CookieManager` for e-commerce scenarios, enabling ads and conversion tracking with URL passthrough. This setup is suitable for sites with online sales and advertising needs. ```typescript ``` -------------------------------- ### Usage Example for createTFunction Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Demonstrates how to use the `createTFunction` to resolve custom and default translations. ```typescript const t = createTFunction( { title: "Custom Title" }, undefined ); const text = t("title"); // "Custom Title" const fallback = t("message"); // Default message ``` -------------------------------- ### Example i18next Translation File with Custom Prefix Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md An example of an i18next translation file structure when using a custom prefix like 'cookies.'. All relevant keys for the cookie manager should be nested under this prefix. ```json { "cookies": { "title": "Cookie Settings 🍪", "message": "We use cookies to improve your experience.", "buttonText": "Allow All", "declineButtonText": "Decline All", "manageButtonText": "Customize", "privacyPolicyText": "Privacy Policy", "manageTitle": "Cookie Preferences", "manageMessage": "Customize your cookie preferences below...", "manageEssentialTitle": "Essential Cookies" // ... include all other translation keys } } ``` -------------------------------- ### Install React Cookie Manager Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Install the library using npm or yarn. This is the first step to integrating cookie consent management into your React application. ```bash npm install react-cookie-manager # or yarn add react-cookie-manager ``` -------------------------------- ### Example: Usage of blockTrackingScripts Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/cookie-blocking.md Shows how to initialize script and iframe blocking with a list of keywords. Demonstrates how matching iframes are replaced with placeholders and scripts are removed. ```typescript blockTrackingScripts(["google", "facebook", "youtube"]) // In page HTML: // // → Replaced with placeholder // // → Removed, not executed ``` -------------------------------- ### Example Translation Object Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/types.md An example of a TranslationObject with custom text for titles, messages, and buttons. ```typescript { title: "Custom Title", message: "Custom message text", buttonText: "Accept All", manageButtonText: "Customize" } ``` -------------------------------- ### Example i18next Translation File (en.json) Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md An example JSON file for English translations when using i18next with React Cookie Manager. It includes keys for the consent banner and other UI elements, prefixed with 'cookies.'. ```json // en.json { "cookies": { "title": "Would You Like A Cookie? 🍪", "message": "We value your privacy. Choose which cookies you want to allow. Essential cookies are always enabled as they are necessary for the website to function properly.", "buttonText": "Accept All", "declineButtonText": "Decline All", "manageButtonText": "Manage Cookies", "privacyPolicyText": "Privacy Policy" } //... } ``` -------------------------------- ### Basic Setup with Analytics Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/README.md Integrate the CookieManager component and conditionally load analytics scripts based on user consent. Ensure the `Analytics` category is consented before executing `window.gtag`. ```typescript { if (consent?.Analytics.consented) { window.gtag?.("consent", "update", { analytics_storage: "granted" }); } }} > ``` -------------------------------- ### Example: Behavior of blockTrackingRequests Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/cookie-blocking.md Demonstrates how fetch requests are handled when certain hosts are blocked. Blocked requests fail with a 403 error, while allowed requests proceed normally. ```typescript // With blockedHosts = ["google-analytics.com"] fetch("https://google-analytics.com/collect", {...}) // Blocked: request fails with 403 .catch(err => console.error(err)) fetch("https://example.com/api", {...}) // Allowed: request proceeds normally .then(res => res.json()) ``` -------------------------------- ### Define and Use Custom Cookie Categories Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Example demonstrating how to define custom cookie categories and override built-in ones using the 'categories' prop. ```jsx import { CookieManager } from "react-cookie-manager"; {children} ``` -------------------------------- ### Basic Cookie Manager Setup Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Wrap your entire application with the CookieManager component to enable cookie consent management. Styles are automatically injected. ```jsx import { CookieManager } from "react-cookie-manager"; createRoot(document.getElementById("root")).render( ); ``` -------------------------------- ### Example: Usage of unblockPreviouslyBlockedContent Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/cookie-blocking.md Demonstrates how to unblock content based on user preferences. Calling with an empty array unblocks everything, while providing specific keywords unblocks only those domains. ```typescript // User accepts all cookies; unblock everything unblockPreviouslyBlockedContent([]) // User updates preferences; unblock permitted domains unblockPreviouslyBlockedContent(["google", "facebook"]) // YouTube still blocked ``` -------------------------------- ### Consent Signal Mapping Example Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/google-consent-mode.md Illustrates how user consent for categories like Analytics, Social, and Advertising is mapped to Google Consent signals. This example shows the emitted signals based on a specific user consent input. ```typescript { analytics_storage: "granted", // Analytics: true ad_storage: "denied", // Advertising: false ad_user_data: "denied", // Advertising: false ad_personalization: "denied", // Advertising: false personalization_storage: "denied", // Social: false functionality_storage: "granted", // Always granted security_storage: "granted" // Always granted } ``` -------------------------------- ### Complete Cookie Manager Configuration Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/configuration.md Use this example to configure all available options for the Cookie Manager component. It covers display settings, cookie storage, user preferences, domain blocking, custom categories, translations, Google Consent Mode integration, custom styling, and callback functions for consent events. ```typescript import { CookieManager } from "react-cookie-manager"; function App() { return ( { if (consent?.Analytics.consented) { initGTAG(); } }} onAccept={() => console.log("All cookies accepted")} onManage={(prefs) => updateTrackingPrefs(prefs)} > ); } ``` -------------------------------- ### Google Consent Mode v2 Configuration Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/README.md Enable Google Consent Mode v2 by configuring the `googleConsentMode` prop. This example sets a `waitForUpdate` delay and enables `urlPassthrough`. ```typescript ``` -------------------------------- ### Basic Cookie Manager Setup Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/usage-examples.md This snippet shows the minimal configuration for the CookieManager component. It defaults to displaying a popup consent UI with standard settings and automatic tracker blocking. ```typescript import { CookieManager } from "react-cookie-manager"; function App() { return ( ); } ``` -------------------------------- ### Analytics-Only Setup for CookieManager Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/google-consent-mode.md Configure `CookieManager` to grant analytics storage by default while denying ads and personalization. This is useful for basic analytics tracking. ```typescript ``` -------------------------------- ### Configure Cookie Manager with Multiple Features Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/usage-examples.md This example shows how to configure the CookieManager component with various options including display settings, storage, categories, translations, Google Consent Mode, callbacks, and styling. It's useful for setting up a comprehensive cookie consent solution. ```typescript import { CookieManager } from "react-cookie-manager"; import { useTranslation } from "react-i18next"; function App() { const { t } = useTranslation(); return ( { if (consent?.Analytics.consented) { window.gtag?.("consent", "update", { analytics_storage: "granted" }); } }} onManage={(prefs) => { logConsentEvent("preferences_saved", prefs); }} // Styling classNames={{ acceptButton: "btn btn-primary", declineButton: "btn btn-secondary", bannerContainer: "shadow-lg rounded-lg", popupContainer: "min-w-80" }} > ); } ``` -------------------------------- ### onConsentLoaded Callback Example Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Demonstrates how to use the `onConsentLoaded` callback to update analytics consent status on initial component mount, based on previously stored consent. ```jsx { if (consent?.Analytics.consented) { window.gtag?.("consent", "update", { analytics_storage: "granted" }); } }} > {children} ``` -------------------------------- ### Customized Cookie Manager with Banner and Styling Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/usage-examples.md This example demonstrates how to customize the CookieManager's appearance and behavior. It uses a banner display type, includes a manage button, and applies custom translations and CSS class names for styling. ```typescript import { CookieManager } from "react-cookie-manager"; function App() { return ( ); } ``` -------------------------------- ### Control Category Visibility in UI Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Example of using the cookieCategories prop to control which categories are displayed in the Manage Preferences UI. ```jsx {children} ``` -------------------------------- ### Strict Compliance Setup for CookieManager Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/google-consent-mode.md Implement strict compliance by denying all consent signals by default until explicit user consent is obtained. This configuration ensures no tracking occurs without user permission. ```typescript ``` -------------------------------- ### Next.js Providers Component Setup Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Sets up the CookieManager within a client component for use with Next.js App Router. Ensure this component is rendered at the root of your application. ```tsx // app/components/Providers.tsx "use client"; import { CookieManager } from "react-cookie-manager"; export function Providers({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### SSR-Safe Cookie and Gtag Functions Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/errors.md Provides examples of SSR-safe utility functions that check for the existence of 'window' before executing, preventing errors during server-side rendering. ```typescript export const setCookie = (name: string, value: string, days: number): void => { if (typeof window === "undefined") return; // SSR-safe // ... rest of implementation } export const ensureGtag = (): ((...args: any[]) => void) | null => { if (typeof window === "undefined") return null; // SSR-safe // ... rest of implementation } ``` -------------------------------- ### Bootstrap Integration for Cookie Manager Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Style the cookie consent UI elements using Bootstrap classes. This example demonstrates applying Bootstrap's button and card classes to various components. ```tsx {children} ``` -------------------------------- ### Get Blocked Hosts Function Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Returns a list of tracker domains to block based on declined categories. If `preferences` is `null` (no consent yet), blocks all built-in trackers. Accepts `CookieCategories` or `null`. ```typescript function getBlockedHosts(preferences: CookieCategories | null): string[] ``` -------------------------------- ### Get Blocked Keywords Function Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Returns a list of keywords (TLD-stripped domain names) to match in scripts and iframe sources. Derived from `getBlockedHosts()`. Accepts `CookieCategories` or `null`. ```typescript function getBlockedKeywords(preferences: CookieCategories | null): string[] ``` -------------------------------- ### Define and Use Custom Cookie Categories Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/usage-examples.md Illustrates how to define custom cookie categories, including overriding built-in ones and adding new ones with specific tracker domains. This example shows how to pass these custom categories to the `CookieManager` component. ```typescript import { CookieManager, type CategoryDefinition } from "react-cookie-manager"; const customCategories: CategoryDefinition[] = [ // Override built-in Analytics { id: "Analytics", title: "Usage Measurement", description: "Help us understand how you use the site" }, // Add custom category { id: "marketing", title: "Marketing Communications", description: "Receive personalized offers and promotions", trackerDomains: ["mailchimp.com", "sendgrid.net"] }, // Add essential category (always on) { id: "essential", title: "Essential Cookies", description: "Required for the website to function", essential: true } ]; function App() { return ( ); } ``` -------------------------------- ### Handle Granular Preferences with OnManage Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/configuration.md The `onManage` callback provides granular control over third-party tools. It allows you to conditionally initialize or disable services like analytics, social widgets, and ad networks based on the `prefs` object. ```typescript { if (!prefs) return; if (prefs.Analytics) { initializeAnalytics(); } else { disableAnalytics(); } if (prefs.Social) { loadSocialWidgets(); } else { hideSocialWidgets(); } if (prefs.Advertising) { initializeAdNetwork(); } else { disableAdNetwork(); } }} > {/* Fine-grained control over third-party tools */} ``` -------------------------------- ### Source Code Organization Structure Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/README.md Provides an overview of the project's directory structure, highlighting key files and their purposes. ```treeview src/ ├── index.ts # Main export file ├── types/types.ts # All type definitions ├── context/CookieConsentContext.tsx # CookieManager & useCookieConsent ├── components/ │ ├── CookieConsenter.tsx # Banner/popup/modal UI │ ├── ManageConsent.tsx # Preferences modal │ └── FloatingCookieButton.tsx # Floating button ├── utils/ │ ├── cookie-utils.ts # Cookie I/O functions │ ├── cookie-blocking/ │ │ ├── index.ts # CookieBlockingManager class │ │ ├── request-blocker.ts # Fetch/XHR interception │ │ └── content-blocker.tsx # Script/iframe blocking │ ├── google-consent-mode.ts # Google Consent Mode functions │ ├── tracker-utils.ts # Tracker domain lookup │ ├── trackers.ts # Base64-encoded blocklists │ ├── translations.ts # Translation system │ ├── categories.ts # Category resolution logic │ └── cn.ts # CSS class merging utility └── styles/tailwind.css # Built-in CSS ``` -------------------------------- ### i18next Configuration for Cookie Manager Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/usage-examples.md Configure i18next with translation resources for cookie-related terms. This setup is used by the CookieManager component via the `translations` prop. ```typescript // i18n.ts import i18n from "i18next"; import { initReactI18next } from "react-i18next"; i18n.use(initReactI18next).init({ resources: { en: { cookies: { title: "Manage Your Cookies", message: "We use cookies to enhance your experience.", buttonText: "Accept", declineButtonText: "Decline", manageButtonText: "Manage", // ... all other translation keys } }, de: { cookies: { title: "Verwalten Sie Ihre Cookies", message: "Wir verwenden Cookies, um Ihr Erlebnis zu verbessern.", // ... } } }, lng: "en", interpolation: { escapeValue: false } }); export default i18n; ``` -------------------------------- ### Run Test Suite Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Executes the project's test suite to ensure code changes are functioning correctly. This command should be run after making changes and before submitting a pull request. ```bash pnpm test ``` -------------------------------- ### Get a Browser Cookie Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Retrieves a cookie by its name. Returns the cookie's value as a string, or null if the cookie is not found. This function is safe for server-side rendering. ```typescript function getCookie(name: string): string | null ``` -------------------------------- ### Override Built-in Category Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/types.md Example of overriding the default 'Analytics' category properties like title, description, and tracker domains. Use built-in `id` values for overrides. ```typescript { id: "Analytics", title: "Usage Stats", description: "Help us understand how you use the site", trackerDomains: ["custom-analytics.example.com"] } ``` -------------------------------- ### Enable Google Consent Mode urlPassthrough Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/google-consent-mode.md Enable the urlPassthrough option to allow Google to measure conversions across different domains by passing consent information via URL parameters. Use this for multi-domain tracking and cross-domain conversion attribution. ```typescript ``` -------------------------------- ### createContentPlaceholder Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/cookie-blocking.md Creates the placeholder UI that replaces a blocked iframe, providing information and management options to the user. ```APIDOC ## createContentPlaceholder ### Description Creates the placeholder UI that replaces a blocked iframe. ### Method Signature ```typescript function createContentPlaceholder( originalElement: HTMLIFrameElement, tFunction: TFunction ): HTMLDivElement ``` ### Parameters * `originalElement` (HTMLIFrameElement) - The iframe element being replaced. * `tFunction` (TFunction) - A translation function for placeholder text. ### Returns A `div` element representing the placeholder UI. ### Placeholder Content - Same width and height as the original iframe. - Message explaining why content is blocked. - Button to open cookie preferences. - Instruction to refresh the page after accepting. - Styled to match the current theme (light/dark). - Data attributes linking it back to the original iframe. ### Default Text - Title: `blockedContentTitle` (default: "Content Blocked") - Message: `blockedContentMessage` (default: explains tracking concern) - Instruction: `blockedContentInstruction` (default: "refresh the page") - Button: `blockedContentButtonText` (default: "Manage Cookie Settings") ``` -------------------------------- ### CookieManager Event Callbacks for User Interaction Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Shows how to handle user acceptance, decline, and custom preference saving using the `onAccept`, `onDecline`, and `onManage` props. This is useful for initializing tools or updating UI based on user choices. ```jsx { console.log("All cookies accepted"); // Initialize analytics tools window.gtag?.("consent", "update", { analytics_storage: "granted" }); }} onDecline={() => { console.log("All cookies declined"); // Ensure tracking is disabled window.gtag?.("consent", "update", { analytics_storage: "denied" }); }} onManage={(preferences) => { console.log("Custom preferences saved:", preferences); // Handle granular consent if (preferences?.Analytics) { // Enable analytics } if (preferences?.Advertising) { // Enable ad personalization } }} > {children} ``` -------------------------------- ### Initialize Tracking Based on User Consent Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/usage-examples.md Manually initialize tracking services like Google Analytics or Facebook Pixel based on the user's consent status obtained via the `useCookieConsent` hook. This ensures that tracking is only enabled when explicitly permitted. ```typescript import { useCookieConsent } from "react-cookie-manager"; import { useEffect } from "react"; function Page() { const { detailedConsent } = useCookieConsent(); // Initialize tracking based on consent useEffect(() => { if (!detailedConsent) return; if (detailedConsent.Analytics.consented) { // Initialize Google Analytics window.gtag?.("config", "GA_ID"); window.gtag?.("event", "page_view"); } if (detailedConsent.Advertising.consented) { // Initialize Facebook Pixel window.fbq?.("init", "PIXEL_ID"); window.fbq?.("track", "PageView"); } if (detailedConsent.Social.consented) { // Load social widgets loadTwitterWidgets(); loadFacebookPlugins(); } }, [detailedConsent]); return
Page content
; } ``` -------------------------------- ### Tailwind CSS Integration for Cookie Manager Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Customize the cookie consent UI using Tailwind CSS classes. This example shows how to apply Tailwind styles to buttons and the banner container. ```tsx {children} ``` -------------------------------- ### Get All Browser Cookies Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Retrieves all cookies as an object where keys are cookie names and values are their corresponding string values. This function is safe for server-side rendering, returning an empty object on the server. ```typescript function getAllCookies(): Record ``` -------------------------------- ### CookieBlockingManager.initialize Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Initializes the CookieBlockingManager. It sets up mutation observers, intercepts network requests, and replaces blocked iframes with placeholders. This method is crucial for enabling the automatic blocking of tracking scripts and other unwanted content. ```APIDOC ## CookieBlockingManager.initialize ### Description Initializes mutation observers, network request interceptors, and replaces blocked iframes with placeholders. ### Method ```typescript initialize(blockedHosts: string[], blockedKeywords: string[], tFunction?: TFunction): void ``` ### Parameters * **blockedHosts** (string[]) - Required - An array of domain hosts that should be blocked in network requests. * **blockedKeywords** (string[]) - Required - An array of keywords used to match against scripts or iframes for blocking. * **tFunction** (TFunction) - Optional - A translation function to be used for the placeholder text displayed for blocked content. ``` -------------------------------- ### Enable Basic Google Consent Mode Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/configuration.md Use `googleConsentMode={true}` for default Google Consent Mode mapping. This emits default consent settings on mount and updates them on consent changes. ```typescript {/* Use default Google Consent Mode mapping */} ``` -------------------------------- ### Integrate React ESLint Plugin Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/playground/README.md Configure ESLint to use the eslint-plugin-react for recommended rules and JSX runtime. Set the React version in the settings and add the plugin to your configuration. ```javascript // eslint.config.js import react from 'eslint-plugin-react' export default tseslint.config({ // Set the react version settings: { react: { version: '18.3' } }, plugins: { // Add the react plugin react, }, rules: { // other rules... // Enable its recommended rules ...react.configs.recommended.rules, ...react.configs['jsx-runtime'].rules, }, }) ``` -------------------------------- ### Define Custom Category Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/types.md Example of defining a new custom cookie category with a unique ID, title, description, and associated tracker domains. Use custom `id` values for new categories. ```typescript { id: "marketing", title: "Marketing", description: "Personalized offers and campaigns", trackerDomains: ["ads.example.com", "marketing.partner.com"] } ``` -------------------------------- ### Initialize CookieBlockingManager Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/cookie-blocking.md Initializes the cookie blocking mechanisms with lists of hosts and keywords to block. Optionally accepts a translation function for placeholder text. Ensure hosts and keywords are correctly formatted for effective blocking. ```typescript class CookieBlockingManager { initialize( blockedHosts: string[], blockedKeywords: string[], tFunction?: TFunction ): void cleanup(): void } ``` ```typescript initialize( blockedHosts: string[], blockedKeywords: string[], tFunction?: TFunction ): void ``` ```typescript const manager = new CookieBlockingManager(); manager.initialize( ["google-analytics.com", "facebook.com"], ["google", "facebook"], tFunction ); ``` -------------------------------- ### Basic CookieManager Usage Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Demonstrates how to integrate the CookieManager component into a React application. Configure display type, theme, and callbacks for user interactions. ```typescript import { CookieManager } from "react-cookie-manager"; function App() { return ( { console.log("Cookies accepted"); // Enable analytics }} onManage={(prefs) => { console.log("Preferences saved:", prefs); }} > ); } ``` -------------------------------- ### Google Consent Mode Helper Imports Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/README.md Import helper functions for managing Google Consent Mode, including setting defaults, updating consent, and mapping consent to signals. ```typescript import { setGoogleConsentDefault, updateGoogleConsent, mapConsentToSignals } from "react-cookie-manager"; ``` -------------------------------- ### Initialize Analytics on Consent Load Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/configuration.md Use the `onConsentLoaded` callback to initialize analytics only if the user has previously consented. This ensures analytics are active on repeat visits without requiring immediate user interaction. ```typescript { if (consent?.Analytics.consented) { // Only initialize analytics if previously consented window.gtag?.("consent", "update", { analytics_storage: "granted" }); // Fire page view or other analytics } }} > {/* Analytics initialized on load if previously consented */} ``` -------------------------------- ### Main Export Import Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/README.md Import the main CookieManager component and the useCookieConsent hook from the library. ```typescript import { CookieManager, useCookieConsent } from "react-cookie-manager"; ``` -------------------------------- ### Configure Advanced Google Consent Mode Options Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/configuration.md Customize Google Consent Mode with advanced options like `waitForUpdate`, `urlPassthrough`, `adsDataRedaction`, custom `mapping`, and `defaults`. This allows fine-grained control over consent signals and their behavior. ```typescript {/* Customized Google Consent Mode integration */} ``` -------------------------------- ### Initialize Cookie Manager in Providers Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/usage-examples.md Set up the CookieManager component in your app's providers file. Configure display type, theme, buttons, and custom translations for the consent popup. ```typescript // app/providers.tsx "use client"; import { CookieManager } from "react-cookie-manager"; import { ReactNode } from "react"; export function Providers({ children }: { children: ReactNode }) { return ( {children} ); } ``` -------------------------------- ### i18next Integration with Custom Prefix Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Demonstrates how to integrate React Cookie Manager with i18next using the `useTranslation` hook. Ensure your i18next configuration includes all necessary translation keys under the specified prefix. ```jsx import { useTranslation } from "react-i18next"; function App() { const { t } = useTranslation(); return ( ); } ``` -------------------------------- ### Initialize Cookie Blocking Manager Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Initializes the CookieBlockingManager by setting up mutation observers, network request interceptors, and replacing blocked iframes with placeholders. Use this to configure which hosts and keywords to block. ```typescript class CookieBlockingManager { initialize(blockedHosts: string[], blockedKeywords: string[], tFunction?: TFunction): void cleanup(): void } ``` -------------------------------- ### getBlockedHosts Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Returns list of tracker domains to block based on declined categories. If `preferences` is `null` (no consent yet), blocks all built-in trackers. ```APIDOC ## getBlockedHosts ### Description Returns list of tracker domains to block based on declined categories. If `preferences` is `null` (no consent yet), blocks all built-in trackers. ### Signature ```typescript function getBlockedHosts(preferences: CookieCategories | null): string[] ``` ``` -------------------------------- ### Google Consent Mode v2 Implementation Flow Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/google-consent-mode.md This flow outlines the sequence of events when Google Consent Mode v2 is implemented, from page load to Google services adjusting data collection based on user consent. ```text 1. Page loads 2. React Cookie Manager calls: gtag('consent', 'default', {denied defaults}) 3. Google Tag Manager waits for consent update (wait_for_update: 500ms default) 4. User makes choice (or no choice within timeout) 5. React Cookie Manager calls: gtag('consent', 'update', {user preferences}) 6. Google services adjust data collection accordingly ``` -------------------------------- ### Advanced Google Consent Mode v2 Configuration Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/google-consent-mode.md Configure advanced Google Consent Mode v2 settings by passing an options object to the `googleConsentMode` prop. This allows customization of wait times, URL passthrough, ad data redaction, signal-to-category mapping, and default consent states. ```typescript ``` -------------------------------- ### Using useCookieConsent Hook Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Demonstrates how to use the useCookieConsent hook in a client component to manage and display cookie consent status. ```tsx // app/page.tsx (client component) "use client"; import { useCookieConsent } from "react-cookie-manager"; export default function Home() { const { showConsentBanner, detailedConsent, openPreferencesModal } = useCookieConsent(); return (
{detailedConsent && (
Analytics: {detailedConsent.Analytics.consented ? "Enabled" : "Disabled"} Social: {detailedConsent.Social.consented ? "Enabled" : "Disabled"} Advertising: {detailedConsent.Advertising.consented ? "Enabled" : "Disabled"}
)}
); } ``` -------------------------------- ### All Available Translation Keys Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md A comprehensive list of all default translation keys available for customization in React Cookie Manager. These cover the consent banner, manage consent modal, cookie sections, status messages, and buttons. ```typescript { // Main consent banner/popup/modal title: "", // Optional title message: "This website uses cookies to enhance your experience.", buttonText: "Accept", declineButtonText: "Decline", manageButtonText: "Manage Cookies", privacyPolicyText: "Privacy Policy", // Manage consent modal manageTitle: "Cookie Preferences", manageMessage: "Manage your cookie preferences below. Essential cookies are always enabled as they are necessary for the website to function properly.", // Essential cookies section manageEssentialTitle: "Essential", manageEssentialSubtitle: "Required for the website to function properly", manageEssentialStatus: "Status: Always enabled", manageEssentialStatusButtonText: "Always On", // Analytics cookies section manageAnalyticsTitle: "Analytics", manageAnalyticsSubtitle: "Help us understand how visitors interact with our website", // Social cookies section manageSocialTitle: "Social", manageSocialSubtitle: "Enable social media features and sharing", // Advertising cookies section manageAdvertTitle: "Advertising", manageAdvertSubtitle: "Personalize advertisements and measure their performance", // Status messages manageCookiesStatus: "Status: {{status}} on {{date}}", // Supports variables manageCookiesStatusConsented: "Consented", manageCookiesStatusDeclined: "Declined", // Buttons in manage modal manageCancelButtonText: "Cancel", manageSaveButtonText: "Save Preferences", // Placeholder shown in place of blocked embedded content (e.g. iframes) blockedContentTitle: "Content Blocked", blockedContentMessage: "This content requires cookies that are currently blocked by your privacy settings. This embedded content may track your activity.", blockedContentInstruction: "After accepting cookies, please refresh the page to view this content.", blockedContentButtonText: "Manage Cookie Settings" } ``` -------------------------------- ### Configure Google Consent Mode v2 Options Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/README.md Customize Google Consent Mode v2 behavior using the `googleConsentMode` prop with an options object. This allows setting wait times, URL passthrough, and ad data redaction. ```jsx ``` -------------------------------- ### Create Content Placeholder UI Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/cookie-blocking.md Generates the placeholder UI element that replaces a blocked iframe. The placeholder includes a message, a button to manage settings, and instructions to refresh the page. ```typescript function createContentPlaceholder( originalElement: HTMLIFrameElement, tFunction: TFunction ): HTMLDivElement ``` -------------------------------- ### createTFunction Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Creates a translation resolver that merges custom translations with defaults. Supports both object maps and i18next-style functions. ```APIDOC ## createTFunction ### Description Creates a translation resolver that merges custom translations with defaults. Supports both object maps and i18next-style functions. ### Signature ```typescript function createTFunction(translations?: TranslationObject | TranslationFunction, translationI18NextPrefix?: string): TFunction ``` ### Usage ```typescript const t = createTFunction( { title: "Custom Title" }, undefined ); const text = t("title"); // "Custom Title" const fallback = t("message"); // Default message ``` ``` -------------------------------- ### GoogleConsentModeOptions Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/google-consent-mode.md Defines the structure for configuring Google Consent Mode. This interface allows customization of how consent signals are mapped and default states are applied. ```APIDOC ## GoogleConsentModeOptions ### Description Configuration options for Google Consent Mode. ### Interface ```typescript interface GoogleConsentModeOptions { waitForUpdate?: number; urlPassthrough?: boolean; adsDataRedaction?: boolean; mapping?: Partial>; defaults?: Partial>; } ``` ### Options | Option | Type | Default | Description | |---|---|---|---| | `waitForUpdate` | `number` | `500` | Milliseconds Google waits for consent update before applying defaults | | `urlPassthrough` | `boolean` | `false` | Enable `gtag('set', 'url_passthrough', true)` for stricter URL measurement | | `adsDataRedaction` | `boolean` | `false` | Enable `gtag('set', 'ads_data_redaction', true)` for sensitive data handling | | `mapping` | `Partial>` | [See default mapping](#default-signal-mapping) | Override which category drives each signal | | `defaults` | `Partial>` | All denied except functionality/security | Pre-consent signal defaults | ## Default Signal Mapping The library maps cookie consent categories to Google signals as follows: | Google Signal | Default Category | Pre-Consent State | |---|---|---| | `analytics_storage` | Analytics | `denied` | | `ad_storage` | Advertising | `denied` | | `ad_user_data` | Advertising | `denied` | | `ad_personalization` | Advertising | `denied` | | `personalization_storage` | Social | `denied` | | `functionality_storage` | — (essential) | `granted` | | `security_storage` | — (essential) | `granted` | ### How It Works When user consent is: ```typescript { Analytics: true, Social: false, Advertising: false } ``` The library emits: ```typescript { analytics_storage: "granted", // Analytics: true ad_storage: "denied", // Advertising: false ad_user_data: "denied", // Advertising: false ad_personalization: "denied", // Advertising: false personalization_storage: "denied", // Social: false functionality_storage: "granted", // Always granted security_storage: "granted" // Always granted } ``` ``` -------------------------------- ### setGoogleConsentDefault Function Source: https://github.com/cookiekit-io/react-cookie-manager/blob/main/_autodocs/api-reference.md Initializes Google Consent Mode v2 with a denied-by-default state. This function should be called early in the application's lifecycle. ```APIDOC ## setGoogleConsentDefault Initialize Google Consent Mode v2 with denied-by-default state. ### Signature ```typescript function setGoogleConsentDefault(options?: GoogleConsentModeOptions): void ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | `options` | `GoogleConsentModeOptions?` | Configuration for defaults, signal mapping, wait time, and flags | ### Description Emits `gtag('consent', 'default', {...})` with the consent state. Call this in a ` ``` ```