# Cookie Consent

> A cookie banner built for UK and EU rules: reject as easily as accept, choose by category, and change your mind later.

Category: Feedback · Free · Updated 2026-11-10 · Live demo: https://www.motionkitui.com/components/cookie-consent

## When to use it

Any site that sets analytics, advertising or other non-essential cookies for visitors in the UK or EU.

## How it works

On first visit it reads any saved choice from localStorage; until it has, nothing renders, so returning visitors never see a flash. Otherwise the banner springs up with Reject all, Customise and Accept all at equal weight. Customise opens a switch for each category, with required ones locked on. The decision is saved with a timestamp and passed to onDecide, which is where you load analytics or marketing scripts. A small Cookie settings button stays behind so the choice can be changed at any time.

## Installation

```bash
npx shadcn@latest add https://www.motionkitui.com/r/cookie-consent.json
```

Or copy `components/motionkit/cookie-consent.tsx` below. Requires react, motion and Tailwind CSS v4. Free for personal projects; commercial use needs MotionKit Plus (https://www.motionkitui.com/pricing).

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `title` | `string` | `"We value your privacy"` | The banner's heading. |
| `description` | `ReactNode` |  | What cookies are used for, in a sentence or two. |
| `categories` | `CookieCategory[]` | `necessary, analytics, marketing` | The choices offered; mark ones that can't be switched off as required. |
| `onDecide` | `(choices: CookieChoices) => void` |  | Called with every category's choice, on a decision and on load if one was saved. Load your scripts from here. |
| `storageKey` | `string \| null` | `"cookie-consent"` | Where the choice is remembered in localStorage; null not to remember it. |
| `policyHref` | `string` |  | A link to your cookie policy. |
| `fixed` | `boolean` | `true` | Pin to the bottom left of the screen; off, it sits in place. |
| `manageButton` | `boolean` | `true` | Leave a small Cookie settings button for changing the choice later. |
| `accent` | `string` | `"#5FAEB4"` | Colour of the switches and the accept button. |

## Accessibility

- **Keyboard: Pass.** Every action is a native button and each category a switch, all reachable with Tab; reopening from Cookie settings moves focus to the banner.
- **Screen readers: Pass.** A labelled region, so it can be found from the landmarks list; category switches announce their state, and required ones are marked unavailable.
- **Reduced motion: Pass.** With reduced motion on, the banner fades in and out instead of sliding, and switches change without travelling.
- **Colour contrast: Pass.** Body text on the panel measures 7:1, and button labels 7.4:1 or more.

## Source

```tsx
"use client";

import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";

export type CookieCategory = {
  id: string;
  label: string;
  description: string;
  /** Always on and can't be switched off, e.g. the cookies that keep someone signed in. */
  required?: boolean;
};

export type CookieChoices = Record<string, boolean>;

type CookieConsentProps = {
  title?: string;
  description?: ReactNode;
  categories?: CookieCategory[];
  /** Called with every category's choice when someone accepts, rejects or saves. Load your scripts from here. */
  onDecide?: (choices: CookieChoices) => void;
  /** Where the choice is remembered in localStorage; null to not remember it (the banner then shows on every load). */
  storageKey?: string | null;
  /** A link to your cookie policy. */
  policyHref?: string;
  /** Pin to the bottom of the screen. Off, it sits in place, which suits previews. */
  fixed?: boolean;
  /** After a choice, leave a small button for changing it later, as UK and EU guidance expects. */
  manageButton?: boolean;
  /** Colour of the switches and the accept button. */
  accent?: string;
  className?: string;
};

const defaultCategories: CookieCategory[] = [
  { id: "necessary", label: "Strictly necessary", description: "Keep the site secure and remember your choices. Always on.", required: true },
  { id: "analytics", label: "Analytics", description: "Help us understand how the site is used, so we can improve it." },
  { id: "marketing", label: "Marketing", description: "Measure campaigns and show you relevant offers elsewhere." },
];

const allSetTo = (categories: CookieCategory[], value: boolean): CookieChoices => Object.fromEntries(categories.map((category) => [category.id, category.required ? true : value]));

/**
 * A cookie banner that meets UK and EU expectations: rejecting is as easy as accepting, nothing optional is on
 * until someone agrees, each category can be chosen separately, and the choice can be changed later. It slides up
 * from the bottom, remembers the decision, and hands it to you to load (or not load) your scripts.
 */
export function CookieConsent({
  title = "We value your privacy",
  description = "We use cookies to run the site and, with your permission, to understand how it's used and to improve our marketing.",
  categories = defaultCategories,
  onDecide,
  storageKey = "cookie-consent",
  policyHref,
  fixed = true,
  manageButton = true,
  accent = "#5FAEB4",
  className = "",
}: CookieConsentProps) {
  const reduceMotion = useReducedMotion();
  const headingId = useId();
  const panelRef = useRef<HTMLDivElement>(null);
  // unknown until the stored choice has been read, so the banner never flashes for someone who has already chosen
  const [state, setState] = useState<"unknown" | "open" | "decided">("unknown");
  const [customising, setCustomising] = useState(false);
  const [choices, setChoices] = useState<CookieChoices>(() => allSetTo(categories, false));

  useEffect(() => {
    const frame = requestAnimationFrame(() => {
      try {
        const saved = storageKey ? JSON.parse(localStorage.getItem(storageKey) ?? "null") : null;
        if (saved?.choices) {
          setChoices(saved.choices);
          setState("decided");
          onDecide?.(saved.choices);
          return;
        }
      } catch {}
      setState("open");
    });
    return () => cancelAnimationFrame(frame);
    // read the stored choice once, on mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function decide(next: CookieChoices) {
    setChoices(next);
    setState("decided");
    setCustomising(false);
    try {
      if (storageKey) localStorage.setItem(storageKey, JSON.stringify({ choices: next, at: new Date().toISOString() }));
    } catch {}
    onDecide?.(next);
  }

  function reopen() {
    setState("open");
    requestAnimationFrame(() => panelRef.current?.focus());
  }

  const position = fixed ? "fixed inset-x-3 bottom-3 z-50 sm:inset-x-auto sm:left-5 sm:bottom-5" : "relative";
  const motionProps = reduceMotion
    ? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }
    : { initial: { opacity: 0, y: 24, scale: 0.98 }, animate: { opacity: 1, y: 0, scale: 1 }, exit: { opacity: 0, y: 16, scale: 0.98 } };
  const button = "inline-flex h-9 flex-1 items-center justify-center whitespace-nowrap rounded-full px-4 text-sm font-medium transition focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#B9C7FF]";

  return (
    <div className={`${position} ${className}`}>
      <AnimatePresence mode="wait">
        {state === "open" && (
          <motion.div
            key="banner"
            ref={panelRef}
            role="region"
            aria-labelledby={headingId}
            tabIndex={-1}
            {...motionProps}
            transition={{ type: "spring", stiffness: 360, damping: 32 }}
            className="w-full max-w-md rounded-2xl border border-white/10 bg-[#141B1B]/95 p-5 text-[#F6F1E8] shadow-2xl shadow-black/50 outline-none backdrop-blur-md"
          >
            <p id={headingId} className="font-medium">
              {title}
            </p>
            <p className="mt-1.5 text-sm leading-6 text-[#94A9A7]">
              {description}
              {policyHref && (
                <>
                  {" "}
                  <a href={policyHref} className="text-[#DCE3E2] underline underline-offset-2 hover:text-[#F6F1E8]">
                    Cookie policy
                  </a>
                </>
              )}
            </p>

            <AnimatePresence initial={false}>
              {customising && (
                <motion.ul
                  initial={{ height: 0, opacity: 0 }}
                  animate={{ height: "auto", opacity: 1 }}
                  exit={{ height: 0, opacity: 0 }}
                  transition={reduceMotion ? { duration: 0 } : { duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
                  className="overflow-hidden"
                >
                  {categories.map((category) => {
                    const on = !!choices[category.id] || !!category.required;
                    return (
                      <li key={category.id} className="mt-3 flex items-start gap-3 rounded-xl border border-white/[0.07] bg-white/[0.02] p-3 first:mt-4">
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-medium">{category.label}</p>
                          <p className="mt-0.5 text-xs leading-5 text-[#94A9A7]">{category.description}</p>
                        </div>
                        <button
                          type="button"
                          role="switch"
                          aria-checked={on}
                          aria-label={category.label}
                          disabled={category.required}
                          onClick={() => setChoices((current) => ({ ...current, [category.id]: !current[category.id] }))}
                          className="relative mt-0.5 h-6 w-10 shrink-0 rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#B9C7FF] disabled:cursor-not-allowed disabled:opacity-60"
                          style={{ backgroundColor: on ? accent : "rgb(255 255 255 / 0.14)" }}
                        >
                          <motion.span
                            aria-hidden
                            className="absolute left-0.5 top-0.5 size-5 rounded-full bg-[#F6F1E8] shadow"
                            initial={false}
                            animate={{ x: on ? 16 : 0 }}
                            transition={reduceMotion ? { duration: 0 } : { type: "spring", stiffness: 600, damping: 34 }}
                          />
                        </button>
                      </li>
                    );
                  })}
                </motion.ul>
              )}
            </AnimatePresence>

            {/* rejecting is offered as plainly as accepting, as UK and EU guidance requires */}
            <div className="mt-4 flex flex-wrap gap-2">
              {customising ? (
                <button type="button" onClick={() => decide({ ...choices, ...Object.fromEntries(categories.filter((c) => c.required).map((c) => [c.id, true])) })} className={`${button} text-[#0C1010]`} style={{ backgroundColor: accent }}>
                  Save choices
                </button>
              ) : (
                <>
                  <button type="button" onClick={() => decide(allSetTo(categories, false))} className={`${button} border border-white/15 hover:border-white/30`}>
                    Reject all
                  </button>
                  <button type="button" onClick={() => setCustomising(true)} className={`${button} border border-white/15 hover:border-white/30`}>
                    Customise
                  </button>
                  <button type="button" onClick={() => decide(allSetTo(categories, true))} className={`${button} text-[#0C1010]`} style={{ backgroundColor: accent }}>
                    Accept all
                  </button>
                </>
              )}
            </div>
          </motion.div>
        )}

        {state === "decided" && manageButton && (
          <motion.button
            key="manage"
            type="button"
            onClick={reopen}
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 8 }}
            transition={{ duration: reduceMotion ? 0 : 0.25 }}
            className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-[#141B1B]/90 px-3.5 py-2 text-xs text-[#DCE3E2] shadow-lg shadow-black/40 backdrop-blur transition hover:border-white/25 hover:text-[#F6F1E8] focus-visible:outline-2 focus-visible:outline-[#B9C7FF]"
          >
            <svg aria-hidden viewBox="0 0 16 16" className="size-3.5">
              <circle cx="8" cy="8" r="6.25" fill="none" stroke="currentColor" strokeWidth="1.4" />
              <circle cx="6" cy="6.5" r="1" fill="currentColor" />
              <circle cx="9.5" cy="9.5" r="1" fill="currentColor" />
              <circle cx="9.75" cy="5.25" r="0.75" fill="currentColor" />
            </svg>
            Cookie settings
          </motion.button>
        )}
      </AnimatePresence>
    </div>
  );
}
```
