3.3.1 • Published 4 months ago

react-cookie-manager v3.3.1

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

🍪 React Cookie Manager

A powerful, customizable React component for cookie consent management with built-in tracking prevention. This component provides a modern, user-friendly way to obtain and manage cookie consent from your website visitors.

React Cookie Manager Hero

React Cookie Manager

Contents

Features

  • 🌐 Multiple display types (banner, popup, modal)
  • 🛡️ Automatic tracking prevention (Google Analytics, etc.)
  • 🎬 Smart iframe blocking for embedded content (YouTube, Vimeo, etc.)
  • 🎯 Granular cookie category controls (Analytics, Social, Advertising)
  • 🎨 Light and dark theme support
  • 📱 Responsive design
  • 🔧 Highly customizable UI
  • 💾 Persistent consent storage
  • 🔒 Privacy-first approach
  • 🇪🇺 GDPR compliance with CookieKit.io integration
  • 🍪 Floating cookie button for easy access

CookieKit Integration

Take your GDPR compliance to the next level with CookieKit.io integration!

Features

  • 📊 Real-time consent analytics dashboard
  • 🔄 Automatic consent proof storage
  • 📈 Advanced user segmentation
  • 🆓 Completely free to use!

Usage with CookieKit

import { CookieManager } from "react-cookie-manager";

function App() {
  return (
    <CookieManager
      cookieKitId="" // Get this from cookiekit.io
      translations={{
        title: "Cookie Preferences",
        message: "We use cookies to improve your experience.",
      }}
    >
      <YourApp />
    </CookieManager>
  );
}

When cookieKitId is provided, React Cookie Manager will automatically:

  • Generate and track unique session IDs
  • Send consent events to CookieKit.io
  • Store consent proofs for GDPR compliance
  • Provide analytics data in your CookieKit dashboard

Visit cookiekit.io to get started for free!

🎮 Try it out!

🔗 Live Demo

See React Cookie Manager in action and explore all its features in our interactive demo.

Automatically Disable Tracking

Unlike other cookie consent managers and React components, this component automatically disables tracking for Google Analytics, Facebook Pixel, and other tracking services. This is done by blocking the tracking scripts from loading. Therefore, you don't need to manually disable tracking, saving you hours of work.

Embedded Content Blocking

React Cookie Manager automatically blocks embedded iframes that would otherwise load cookies without consent, such as:

  • YouTube videos
  • Vimeo videos
  • Google Maps
  • Social media embeds (Twitter, Instagram, etc.)
  • Third-party widgets and tools

When a user hasn't consented to the required cookies, these embeds are replaced with user-friendly placeholders that:

  • Explain why the content is blocked
  • Provide a button to manage cookie settings
  • Inform users to refresh the page after accepting cookies
  • Maintain the same dimensions as the original content

This ensures your site remains GDPR-compliant while providing a seamless user experience.

Installation

npm install react-cookie-manager
# or
yarn add react-cookie-manager

Importing Styles

The component requires its CSS file to be imported in your application. Add the following import to your app's entry point (e.g., App.tsx or index.tsx):

import "react-cookie-manager/style.css";

React Cookie Manager Styles

Basic Usage

import { CookieManager } from "react-cookie-manager";
import "react-cookie-manager/style.css";

function App() {
  return (
    <CookieManager
      translations={{
        title: "Cookie Preferences",
        message: "We use cookies to improve your experience.",
      }}
      onManage={(preferences) =>
        console.log("Cookie preferences:", preferences)
      }
    >
      <YourApp />
    </CookieManager>
  );
}

Next.js Usage

For Next.js applications, you'll need to use dynamic imports to prevent SSR of the cookie manager:

"use client";

import dynamic from "next/dynamic";

const CookieManager = dynamic(
  () => import("react-cookie-manager").then((mod) => mod.CookieManager),
  { ssr: false, loading: () => null }
);

// In your Providers component or layout
export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <CookieManager
      showManageButton={true}
      translations={{
        title: "Cookie Preferences",
        message: "We use cookies to improve your experience.",
      }}
      displayType="banner"
      theme="light"
    >
      {children}
    </CookieManager>
  );
}

// In your page component
import { useCookieConsent } from "react-cookie-manager";

export default function Home() {
  const { showConsentBanner, detailedConsent } = useCookieConsent();

  return (
    <div>
      <button onClick={showConsentBanner}>Manage Cookie Settings</button>
      {detailedConsent && (
        <div>
          Analytics:{" "}
          {detailedConsent.Analytics.consented ? "Enabled" : "Disabled"}
          Social: {detailedConsent.Social.consented ? "Enabled" : "Disabled"}
          Advertising:{" "}
          {detailedConsent.Advertising.consented ? "Enabled" : "Disabled"}
        </div>
      )}
    </div>
  );
}

Full Usage

import { CookieManager } from "react-cookie-manager";
import "react-cookie-manager/style.css";

function App() {
  return (
    <CookieManager
      translations={{
        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",
      }}
      showManageButton={true}
      privacyPolicyUrl="https://example.com/privacy"
      theme="light"
      displayType="popup"
      cookieKitId="your-cookie-kit-id" // Optional: Enable CookieKit.io integration
      onManage={(preferences) => {
        if (preferences) {
          console.log("Cookie preferences updated:", preferences);
        }
      }}
    >
      <AppContent />
    </CookieManager>
  );
}

Advanced Usage with Hook

import { CookieManager, useCookieConsent } from "react-cookie-manager";

function CookieSettings() {
  const { showConsentBanner, detailedConsent } = useCookieConsent();

  return (
    <div>
      <button onClick={showConsentBanner}>Manage Cookie Settings</button>
      {detailedConsent && (
        <div>
          Analytics:{" "}
          {detailedConsent.Analytics.consented ? "Enabled" : "Disabled"}
          Social: {detailedConsent.Social.consented ? "Enabled" : "Disabled"}
          Advertising:{" "}
          {detailedConsent.Advertising.consented ? "Enabled" : "Disabled"}
        </div>
      )}
    </div>
  );
}

Floating Cookie Button

The floating cookie button provides a persistent, accessible way for users to manage their cookie preferences after they've made their initial choice. It appears as a small, animated cookie icon in the bottom-left corner of the screen.

Enabling the Floating Button

<CookieManager
  enableFloatingButton={true}
  theme="light" // or "dark"
  // ... other props
>
  <YourApp />
</CookieManager>

Features

  • 🎯 Automatically appears after initial consent
  • 🎨 Matches your theme (light/dark mode)
  • 🔄 Smooth animations and hover effects
  • ❌ Dismissible with a close button
  • 📱 Responsive and mobile-friendly
  • 🎛️ Easy access to cookie preferences

Behavior

  1. The button appears after users make their initial cookie choice
  2. Hovering reveals a close button to dismiss the floating button
  3. Clicking opens the cookie preferences modal
  4. The button remains hidden until page refresh after being closed
  5. Maintains position during scroll

Customization

The floating button automatically adapts to your chosen theme:

// Light theme (default)
<CookieManager
  enableFloatingButton={true}
  theme="light"
>
  <YourApp />
</CookieManager>

// Dark theme
<CookieManager
  enableFloatingButton={true}
  theme="dark"
>
  <YourApp />
</CookieManager>

The button inherits your color scheme:

  • Light theme: White background with gray text
  • Dark theme: Black background with light gray text

Accessibility

The floating button is fully accessible:

  • Proper ARIA labels
  • Keyboard navigation support
  • Focus management
  • High contrast ratios
  • Screen reader friendly

Props

PropTypeDefaultDescription
childrenReact.ReactNode-Your app components
translationsTranslationObject | TranslationFunction-Translation object or i18n TFunction
translationI18NextPrefixstring-i18next key prefix, e.g. "cookies."
showManageButtonbooleanfalseWhether to show the manage cookies button
enableFloatingButtonbooleanfalseEnable floating cookie button
privacyPolicyUrlstring-URL for the privacy policy
cookieKeystring'cookie-consent'Name of the cookie to store consent
cookieExpirationnumber365Days until cookie expires
displayType'banner' | 'popup' | 'modal''banner'How the consent UI is displayed
position'top' | 'bottom''bottom'Position of the banner
theme'light' | 'dark''light'Color theme
disableAutomaticBlockingbooleanfalseDisable automatic tracking prevention
blockedDomainsstring[][]Additional domains to block
cookieKitIdstringundefinedYour CookieKit.io integration ID
onManage(preferences?: CookieCategories) => void-Callback when preferences are updated

Cookie Categories

The component manages three categories of cookies:

interface CookieCategories {
  Analytics: boolean;
  Social: boolean;
  Advertising: boolean;
}

Hook API

The useCookieConsent hook provides the following:

interface CookieConsentHook {
  hasConsent: boolean | null;
  isDeclined: boolean;
  detailedConsent: DetailedCookieConsent | null;
  showConsentBanner: () => void;
  acceptCookies: () => void;
  declineCookies: () => void;
  updateDetailedConsent: (preferences: CookieCategories) => void;
}

i18next support

import { default as i18next } from "i18next";

function App() {
  return (
    <CookieManager
      translations={i18next.t}
      translationI18NextPrefix="cookies."
      ...
      />
  )
}
// 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"
  }
  //...
}

Translation Options

All available translation keys and their default values:

{
  // 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"
}

You can override any of these translations by passing them in the translations prop:

<CookieManager
  translations={{
    title: "Cookie Settings 🍪",
    message: "We use cookies to improve your experience.",
    buttonText: "Allow All",
    manageButtonText: "Customize",
    // ... override any other translations
  }}
>
  <App />
</CookieManager>

i18next Integration

When using i18next, make sure your translation files include all the keys under your chosen prefix:

{
  "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
  }
}

Then use it with the i18next translation function:

import { useTranslation } from "react-i18next";

function App() {
  const { t } = useTranslation();

  return (
    <CookieManager translations={t} translationI18NextPrefix="cookies.">
      <YourApp />
    </CookieManager>
  );
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT © Hypership

3.3.1

4 months ago

3.3.0

4 months ago

3.2.0

5 months ago

3.1.0

5 months ago

3.0.0

5 months ago

2.2.6

5 months ago

2.2.5

5 months ago

2.2.4

5 months ago

2.2.3

5 months ago

2.2.2

5 months ago

2.2.1

5 months ago

2.2.0

5 months ago

2.1.3

5 months ago

2.1.2

5 months ago

2.1.1

5 months ago

2.1.0

5 months ago

2.0.0

5 months ago

1.4.6

5 months ago

1.4.5

5 months ago

1.4.4

5 months ago

1.4.3

5 months ago

1.4.2

5 months ago

1.4.1

5 months ago

1.4.0

5 months ago

1.3.1

5 months ago

1.3.0

5 months ago

1.2.0

5 months ago

1.1.0

6 months ago

1.0.24

6 months ago

1.0.23

6 months ago

1.0.22

6 months ago

1.0.21

6 months ago

1.0.20

6 months ago

1.0.19

6 months ago

1.0.18

6 months ago

1.0.17

6 months ago

1.0.16

6 months ago

1.0.15

6 months ago

1.0.14

6 months ago

1.0.11

6 months ago

1.0.10

6 months ago

1.0.9

6 months ago

1.0.8

6 months ago

1.0.7

6 months ago

1.0.6

6 months ago

1.0.5

6 months ago

1.0.4

6 months ago

1.0.3

6 months ago

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

12 months ago