React Integration

React Cookie ConsentDeveloper-First Solution

Complete React cookie consent integration guide. NPM package, component implementation, SSR support, TypeScript definitions. GDPR, PIPEDA, CCPA compliant React components for modern web applications.

Why React Developers Choose Our Solution

Built specifically for modern React applications and developer workflows

NPM Package

Install via npm/yarn with full TypeScript support, tree-shaking, and modern ES modules.

React Components

Pre-built React components with hooks, context, and full customization options.

SSR Support

Full server-side rendering support for Next.js, Gatsby, and other React frameworks.

TypeScript Ready

Complete TypeScript definitions, interfaces, and type safety for modern React development.

Performance Optimized

Minimal bundle size, lazy loading, and optimized for React's reconciliation process.

Developer Experience

Intuitive API, comprehensive documentation, and excellent developer tools integration.

Installation & Setup

Get started with React cookie consent in minutes

Install Package

Install via your preferred package manager

# Using npm
npm install @cookiebanner/react

# Using yarn
yarn add @cookiebanner/react

# Using pnpm
pnpm add @cookiebanner/react

Package includes:

  • React components and hooks
  • TypeScript definitions
  • CSS styles and themes
  • Utility functions

Basic Implementation

Simple component integration

import React from 'react';
import { CookieBanner, ConsentProvider } from '@cookiebanner/react';

function App() {
  return (
    <ConsentProvider>
      <div className="App">
        <CookieBanner />
        {/* Your app content */}
      </div>
    </ConsentProvider>
  );
}

export default App;

That's it! The cookie banner will automatically appear and handle consent management.

Configuration

Customize the banner to your needs

import { CookieBanner, ConsentProvider } from '@cookiebanner/react';

const config = {
  compliance: 'gdpr',
  position: 'bottom-right',
  theme: 'dark',
  languages: ['en', 'es', 'fr'],
  analytics: {
    googleAnalytics: 'GA_MEASUREMENT_ID'
  }
};

function App() {
  return (
    <ConsentProvider config={config}>
      <CookieBanner />
    </ConsentProvider>
  );
}

Next.js Integration

Server-side rendering support

// pages/_app.tsx or app/layout.tsx
import { ConsentProvider } from '@cookiebanner/react';

export default function MyApp({ Component, pageProps }) {
  return (
    <ConsentProvider>
      <Component {...pageProps} />
    </ConsentProvider>
  );
}

// pages/_document.tsx (optional)
import { Html, Head, Main, NextScript } from 'next/document';
import { CookieScripts } from '@cookiebanner/react';

export default function Document() {
  return (
    <Html>
      <Head>
        <CookieScripts />
      </Head>
      <Body>
        <Main />
        <NextScript />
      </Body>
    </Html>
  );
}

React Hooks & API

Powerful hooks and utilities for advanced React applications

useConsent Hook

Access consent state and controls

import { useConsent } from '@cookiebanner/react';

function MyComponent() {
  const {
    hasConsent,
    getConsent,
    updateConsent,
    showBanner,
    hideBanner,
    consentState
  } = useConsent();

  // Check if user has given consent for analytics
  const canTrackAnalytics = hasConsent('analytics');

  // Get specific consent category
  const analyticsConsent = getConsent('analytics');

  // Update consent programmatically
  const handleAcceptAll = () => {
    updateConsent({
      necessary: true,
      analytics: true,
      marketing: true
    });
  };

  return (
    <div>
      {canTrackAnalytics && <AnalyticsComponent />}
      <button onClick={handleAcceptAll}>
        Accept All Cookies
      </button>
    </div>
  );
}

useConsentManager Hook

Advanced consent management

import { useConsentManager } from '@cookiebanner/react';

function ConsentManager() {
  const {
    consentCategories,
    updateCategory,
    resetConsent,
    exportConsent,
    importConsent,
    consentHistory
  } = useConsentManager();

  // Update specific category
  const handleCategoryChange = (category, value) => {
    updateCategory(category, value);
  };

  // Reset all consent
  const handleReset = () => {
    resetConsent();
  };

  // Export consent data
  const handleExport = () => {
    const data = exportConsent();
    console.log('Consent data:', data);
  };

  return (
    <div>
      {Object.entries(consentCategories).map(([category, config]) => (
        <div key={category}>
          <label>
            <input
              type="checkbox"
              checked={config.consented}
              onChange={(e) => handleCategoryChange(category, e.target.checked)}
            />
            {config.name}
          </label>
        </div>
      ))}
      <button onClick={handleReset}>Reset Consent</button>
      <button onClick={handleExport}>Export Data</button>
    </div>
  );
}

Conditional Rendering

Render components based on consent

import { useConsent, ConsentGate } from '@cookiebanner/react';

// Method 1: Using hooks
function AnalyticsComponent() {
  const { hasConsent } = useConsent();
  
  if (!hasConsent('analytics')) {
    return <div>Analytics disabled</div>;
  }

  return <div>Analytics tracking active</div>;
}

// Method 2: Using ConsentGate component
function App() {
  return (
    <div>
      <ConsentGate category="analytics">
        <GoogleAnalytics />
      </ConsentGate>
      
      <ConsentGate category="marketing">
        <FacebookPixel />
      </ConsentGate>
      
      <ConsentGate category="necessary">
        <EssentialScripts />
      </ConsentGate>
    </div>
  );
}

TypeScript Support

Complete type safety and IntelliSense support

Type Definitions

// Fully typed configuration
interface ConsentConfig {
  compliance: 'gdpr' | 'pipeda' | 'ccpa' | 'custom';
  position: 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
  theme: 'light' | 'dark' | 'auto';
  languages: string[];
  analytics?: {
    googleAnalytics?: string;
    facebookPixel?: string;
  };
  categories: {
    necessary: CategoryConfig;
    analytics: CategoryConfig;
    marketing: CategoryConfig;
    functionality: CategoryConfig;
  };
}

interface CategoryConfig {
  name: string;
  description: string;
  required: boolean;
  cookies: string[];
}
  • Complete interface definitions
  • Hook return type safety
  • Event handler types

Hook Types

// Typed hook returns
interface ConsentHookReturn {
  hasConsent: (category: ConsentCategory) => boolean;
  getConsent: (category: ConsentCategory) => ConsentState;
  updateConsent: (consent: ConsentMap) => void;
  showBanner: () => void;
  hideBanner: () => void;
  consentState: ConsentState;
}

type ConsentCategory = 'necessary' | 'analytics' | 'marketing' | 'functionality';

interface ConsentState {
  consented: boolean;
  timestamp: string;
  version: string;
  categories: Record<ConsentCategory, boolean>;
}

// Usage with full type safety
const MyComponent: React.FC = () => {
  const { hasConsent, updateConsent } = useConsent();
  
  // TypeScript will enforce correct category names
  const analyticsAllowed = hasConsent('analytics');
  
  // Type-safe consent updates
  updateConsent({
    analytics: true,
    marketing: false
  });
  
  return <div>Analytics: {analyticsAllowed ? 'Enabled' : 'Disabled'}</div>;
};
  • Autocomplete for category names
  • Compile-time error checking
  • Refactoring support

Ready to Build Compliant React Apps?

Join thousands of React developers using our cookie consent solution. TypeScript support, modern hooks, and seamless integration with your favorite frameworks.