react-consent-bar
v1.0.0
Published
React components and hooks for a consent banner that helps with India's DPDP Act and GDPR. Consent per purpose, easy withdrawal, 23 languages. Built on consentbar.
Maintainers
Readme
react-consent-bar
React components and hooks for a consent banner. Users choose what you may use their data for, and can change their mind at any time. 23 languages.
Live demo: try the banner, switch between 23 languages and watch the events.
react-consent-bar is built on consentbar. consentbar draws the banner and the preferences panel, saves the user's choice and keeps a record of it. This package adds what a React app needs on top:
- A provider that creates the bar once and removes it when it is no longer needed.
- Hooks that tell your components what the user allowed, and re-render them when it changes.
- Components that show content only after consent, and a button that opens the preferences panel.
consentbar is made for India's data protection law: the Digital Personal Data Protection (DPDP) Act, 2023 and the DPDP Rules, 2025. It also works for European-style (GDPR) cookie consent.
Important: react-consent-bar helps you follow the DPDP consent rules. It does not make your website legally compliant on its own. This page is not legal advice.
Using Next.js? Use next-consent-bar. It has everything in this package, plus server helpers that avoid a flash of wrong content.
Features
- A provider and hooks.
useConsent()gives you the user's choices and re-renders your component when they change. - Show content only after consent.
<ConsentGate purpose="marketing">hides a video, a map or a chat widget until the user allows it. - A ready-made placeholder.
<ConsentPlaceholder>explains why the content is hidden and has an "Allow" button. - A privacy choices button for your footer, so users can change or withdraw consent at any time.
- Safe with server-side rendering. Nothing touches
windowon the server. Content that needs consent shows its fallback there. - Works in React Strict Mode. One banner, no leftover listeners.
- Everything from consentbar: consent per purpose, "Reject all" as easy as "Accept all", English and the 22 languages of the Eighth Schedule, consent records, and script blocking.
- Small. About 2 KB (compressed) on top of consentbar. TypeScript types included.
Installation
If your project uses npm:
npm install react-consent-barOr with another package manager:
pnpm add react-consent-bar
yarn add react-consent-bar
bun add react-consent-barconsentbar is installed with it. You need React 18 or newer.
Quick start
Set it up in 3 steps
Step 1. Write your config. List your purposes and your contact details. A purpose is one reason you use personal data, such as "Analytics". Put the config in its own file, outside any component:
// src/consent-config.ts
import type { ConsentBarConfig } from 'react-consent-bar'
export const consentConfig: ConsentBarConfig = {
purposes: [
{ id: 'essential', title: 'Essential', description: 'Keeps you signed in and protects your account.', required: true },
{ id: 'analytics', title: 'Analytics', description: 'Counts visits so we can improve the site.' },
{ id: 'marketing', title: 'Marketing', description: 'Shows videos and offers from other sites.' },
],
notice: {
fiduciaryName: 'Example Pvt Ltd',
privacyPolicyUrl: 'https://example.in/privacy',
contactEmail: '[email protected]',
},
}Step 2. Wrap your app in the provider.
import { ConsentBarProvider } from 'react-consent-bar'
import { consentConfig } from './consent-config'
export function Root() {
return (
<ConsentBarProvider config={consentConfig}>
<App />
</ConsentBarProvider>
)
}Step 3. Use consent in your components.
import { ConsentGate, ConsentPlaceholder, useHasConsent } from 'react-consent-bar'
function VideoSection() {
return (
<ConsentGate purpose="marketing" fallback={<ConsentPlaceholder purpose="marketing" />}>
<iframe src="https://www.youtube-nocookie.com/embed/VIDEO_ID" title="Product video" />
</ConsentGate>
)
}
function AnalyticsStatus() {
const allowed = useHasConsent('analytics')
return <p>Analytics is {allowed ? 'on' : 'off'}.</p>
}That's it. The banner shows the first time someone visits. After they choose, it hides, and a small "Privacy choices" button stays in the corner.
Without hooks
If you only want the banner, add <ConsentBar> once, anywhere in your app. It renders nothing itself:
import { ConsentBar } from 'react-consent-bar'
import { consentConfig } from './consent-config'
export function App() {
return (
<>
<ConsentBar config={consentConfig} />
<Home />
</>
)
}Table of contents
Usage
Wrap your app
A provider is a component that wraps your app and shares data with every component inside it. <ConsentBarProvider> creates the consent bar and shares it with the hooks and components of this package.
<ConsentBarProvider config={consentConfig}>
<App />
</ConsentBarProvider>Things to know:
- The bar is created after the first render, in the browser. It is never created on the server. It is removed when the provider unmounts.
- Keep
configstable. Define it outside your components (as in the quick start), or wrap it inuseMemo(). When you pass a new config object, the bar is removed and created again. If you write the object inline in JSX, it is new on every render. - Use one provider per page. Two providers would show two banners.
- React Strict Mode is fine. In development, Strict Mode runs effects twice to find bugs. The provider removes the first bar before it creates the second, so you see one banner.
If your config depends on props or state, memoize it:
function Root({ language }: { language: string }) {
const config = useMemo(() => ({ ...consentConfig, language }), [language])
return (
<ConsentBarProvider config={config}>
<App />
</ConsentBarProvider>
)
}All consentbar options work in config: version, expiresAfterDays, languages, texts, position, theme, cssVars, recordEndpoint and the rest. See the consentbar README for the full list.
Check consent in a component
A hook is a function whose name starts with use. You call it at the top of a React component. useConsent() returns the user's choices and functions to change them. Your component re-renders when the choices change.
import { useConsent } from 'react-consent-bar'
function ConsentSettings() {
const { ready, decided, hasConsent, update, withdraw, openPreferences } = useConsent()
if (!ready) return <p>Loading your privacy choices...</p>
return (
<div>
<p>{decided ? 'You have made your choice.' : 'You have not chosen yet.'}</p>
<label>
<input
type="checkbox"
checked={hasConsent('marketing')}
onChange={(event) => update({ marketing: event.target.checked })}
/>
Marketing
</label>
<button onClick={() => withdraw()}>Withdraw all consent</button>
<button onClick={openPreferences}>Open privacy choices</button>
</div>
)
}If you only need one purpose, useHasConsent() is shorter. Use it to start a tool only after consent:
import { useEffect } from 'react'
import { useHasConsent } from 'react-consent-bar'
function Analytics() {
const allowed = useHasConsent('analytics')
useEffect(() => {
if (allowed) startAnalytics()
}, [allowed])
return null
}Before the bar is ready, and on the server, every purpose that is not required is false. The bar is ready right after the first render in the browser. ready tells you when it is. Functions like acceptAll() do nothing before then.
Show content only after consent
<ConsentGate> shows its children only when the purpose is allowed. Otherwise it shows fallback (nothing by default):
import { ConsentGate, ConsentPlaceholder } from 'react-consent-bar'
<ConsentGate purpose="marketing" fallback={<ConsentPlaceholder purpose="marketing" />}>
<iframe src="https://www.youtube-nocookie.com/embed/VIDEO_ID" title="Product video" />
</ConsentGate>The iframe is not in the page until the user allows "Marketing", so the other site gets no data before that.
To need more than one purpose, pass a list. Every purpose in it must be allowed:
<ConsentGate purpose={['analytics', 'marketing']}>
<PersonalisedOffers />
</ConsentGate><ConsentPlaceholder> is a small box with a message and two buttons:
- "Allow Marketing" turns that purpose on. The content appears at once.
- "Privacy choices" opens the preferences panel.
It uses the purpose title from your config, in the current language. It has simple built-in styles, so it looks fine without any CSS. You can change the texts and the look:
<ConsentPlaceholder
purpose="marketing"
message="Videos are turned off."
allowLabel="Turn on videos"
preferencesLabel="Settings"
className="video-placeholder"
style={{ minHeight: 200 }}
/>style is added on top of the built-in styles. To style it only with your own CSS, add unstyled.
Note: once a script or iframe has loaded, it cannot be stopped. When the user withdraws consent, <ConsentGate> removes the content, but code that already ran may keep running. Reload the page if you need a clean start.
Add a privacy choices button
The DPDP Act says withdrawing consent must be as easy as giving it. consentbar shows a small floating button for this. Many sites also add a link in the footer. <PrivacyChoicesButton> is a <button> that opens the preferences panel:
import { PrivacyChoicesButton } from 'react-consent-bar'
function Footer() {
return (
<footer>
<a href="/privacy">Privacy policy</a>
<PrivacyChoicesButton className="footer-link" />
</footer>
)
}The text is "Privacy choices" unless you pass your own children. It takes every normal button prop, like className, style, id and onClick:
<PrivacyChoicesButton className="footer-link">Cookie settings</PrivacyChoicesButton>If you show this button on every page, you can hide the floating one with floatingButton: false in your config.
Use it with Vite or Create React App
Add the provider where your app starts. With Vite, that is src/main.tsx. With Create React App, it is src/index.tsx. The code is the same:
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { ConsentBarProvider } from 'react-consent-bar'
import { consentConfig } from './consent-config'
import App from './App'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<ConsentBarProvider config={consentConfig}>
<App />
</ConsentBarProvider>
</StrictMode>,
)You can still block scripts in index.html with consentbar's data-consent attribute. consentbar runs them when the user agrees:
<script type="text/plain" data-consent="analytics" src="https://www.googletagmanager.com/gtag/js?id=G-XXXX" async></script>See Load scripts only after consent in the consentbar README.
Change languages and texts
Language and text options go straight to consentbar. All 23 languages are included. To show only some of them, and to change texts:
export const consentConfig: ConsentBarConfig = {
purposes: [
{ id: 'essential', title: { en: 'Essential', hi: 'आवश्यक' }, description: { en: 'Keeps you signed in.', hi: 'आपको साइन इन रखता है।' }, required: true },
{ id: 'analytics', title: { en: 'Analytics', hi: 'विश्लेषण' }, description: { en: 'Counts visits.', hi: 'विज़िट गिनता है।' } },
],
notice: { fiduciaryName: 'Example Pvt Ltd', privacyPolicyUrl: '/privacy', contactEmail: '[email protected]' },
languages: ['en', 'hi', 'ta'],
texts: {
en: { acceptAll: 'Allow all', bannerTitle: 'Your data, your choice' },
},
}To read or change the language from a component:
function LanguagePicker() {
const { language, setLanguage } = useConsent()
return (
<select value={language} onChange={(event) => setLanguage(event.target.value)}>
<option value="en">English</option>
<option value="hi">हिन्दी</option>
<option value="ta">தமிழ்</option>
</select>
)
}setLanguage() throws an error for a language that is not in languages. All text names are listed in the consentbar README. The texts of <ConsentPlaceholder> and <PrivacyChoicesButton> are yours: pass them as props in the language you need.
TypeScript
Types are included. The useful consentbar types are exported from this package too, so you need only one import:
import type {
ConsentBarConfig,
ConsentSnapshot,
ConsentRecord,
InitialConsent,
Purpose,
UseConsentResult,
} from 'react-consent-bar'
const purposes: Purpose[] = [
{ id: 'essential', title: 'Essential', description: 'Keeps you signed in.', required: true },
]For other libraries that ask "is this purpose allowed?", use consentChecker() with the controller:
import { consentChecker, useConsent } from 'react-consent-bar'
function useIsAllowed() {
const { controller } = useConsent()
return controller ? consentChecker(controller) : () => false
}API
ConsentBarProvider
<ConsentBarProvider config={config} initialConsent={initialConsent}>{children}</ConsentBarProvider>| Prop | Type | Default | What it does |
|---|---|---|---|
| config | ConsentBarConfig | required | The consentbar config. Keep it stable. A new object creates the bar again. |
| initialConsent | InitialConsent | none | The consent to use on the server and in the first render. Only the first value is used. |
| children | ReactNode | none | Your app. |
ConsentBar
<ConsentBar config={config} />| Prop | Type | Default | What it does |
|---|---|---|---|
| config | ConsentBarConfig | required | The consentbar config. Adds the bar and renders nothing. Hooks do not work with it. |
useConsent()
function useConsent(): UseConsentResultMust be used inside <ConsentBarProvider>. Throws an error outside it.
| Field | Type | What it does |
|---|---|---|
| ready | boolean | true once the bar exists in the browser. Always false on the server. |
| decided | boolean | true when the user has made a choice that is still valid. |
| purposes | Record<string, boolean> | Every purpose id with true or false. Required purposes are always true. |
| hasConsent(id) | boolean | true when the purpose is allowed. Unknown ids give false. |
| acceptAll() | ConsentRecord \| undefined | Allows every purpose and saves. |
| rejectAll() | ConsentRecord \| undefined | Refuses every purpose that is not required, and saves. |
| update(choices) | ConsentRecord \| undefined | Changes some purposes and saves, like update({ analytics: true }). |
| withdraw(id?) | ConsentRecord \| undefined | Takes back consent for one purpose, or for all that are not required. |
| openPreferences() | nothing | Opens the preferences panel. |
| language | string | The current language code. |
| setLanguage(code) | nothing | Changes the language. |
| controller | ConsentBarController \| null | The consentbar controller, for everything else. null before ready. |
The functions do nothing (and return undefined) before ready.
useHasConsent(purposeId)
function useHasConsent(purposeId: string): booleanReturns true when the purpose is allowed. Re-renders when that changes. Must be used inside the provider.
ConsentGate
| Prop | Type | Default | What it does |
|---|---|---|---|
| purpose | string \| string[] | required | The purpose id. With a list, every purpose must be allowed. |
| fallback | ReactNode | null | What to show without consent. |
| children | ReactNode | none | What to show with consent. |
ConsentPlaceholder
| Prop | Type | Default | What it does |
|---|---|---|---|
| purpose | string \| string[] | required | The purpose the hidden content needs. "Allow" turns on every purpose listed. |
| message | ReactNode | "This content needs your consent for {title}." | The message. |
| allowLabel | ReactNode | "Allow {title}" | Text of the button that allows the purpose. |
| preferencesLabel | ReactNode | "Privacy choices" | Text of the button that opens the panel. |
| className | string | none | A class for the box. |
| style | CSSProperties | none | Styles for the box, added on top of the built-in styles. |
| unstyled | boolean | false | Removes the built-in styles. |
It renders nothing once the purpose is allowed.
PrivacyChoicesButton
| Prop | Type | Default | What it does |
|---|---|---|---|
| children | ReactNode | "Privacy choices" | The button text. |
| onClick | function | none | Runs first. Call event.preventDefault() to stop the panel from opening. |
| any <button> prop | | | Passed to the button. type defaults to "button". A ref reaches the button. |
consentChecker(controller)
function consentChecker(controller: ConsentBarController): (purpose: string) => booleanRe-exported from consentbar. Gives you a function that returns true when a purpose is allowed.
Types
InitialConsent, UseConsentResult, ConsentBarProviderProps, ConsentBarProps, ConsentGateProps, ConsentPlaceholderProps, PrivacyChoicesButtonProps, and from consentbar: ConsentBarConfig, ConsentBarController, ConsentBarEvent, ConsentBarEventMap, ConsentSnapshot, ConsentRecord, ConsentAction, Purpose, NoticeDetails, LocalizedText, LocalizedList, ConsentBarLanguage, ConsentBarLanguageInput, ConsentBarTexts, TextKey.
InitialConsent needs only decided and purposes. A ConsentSnapshot from consentbar fits it:
interface InitialConsent {
decided: boolean
purposes: Record<string, boolean>
language?: string | null
noticeVersion?: string
timestamp?: string | null
recordId?: string | null
}Notes and limitations
- Not legal advice. This package helps with the DPDP consent rules. It does not make your site compliant on its own. See the DPDP checklist in the consentbar README.
- Server-side rendering. On the server, nothing is known about the user's choice, so content in
<ConsentGate>shows its fallback. In the browser it switches right after the first render. To avoid this switch, passinitialConsent, read from the cookie on the server. next-consent-bar does this for Next.js. - Server Components. Every file in this package starts with
"use client". A Client Component is a component that also runs in the browser. You can render the provider and the components from a Server Component, butconfigmust then be plain data, without functions likeonConsent. - Keep
configstable. A new config object removes the bar and creates it again. - One provider per page. Two providers would show two banners.
- Scripts that already ran keep running after a user withdraws consent. Reload the page if needed.
- Translations need checking. No native speaker has reviewed consentbar's Indian language texts yet. See Notes and limitations in the consentbar README.
- Importing consentbar yourself. consentbar is installed with this package. With pnpm, you can only import it directly (for example
consentbar/languages/hi) if you add it to your ownpackage.jsontoo.
Requirements
- React 18 or newer, and react-dom.
- A web browser to show the bar. Server-side rendering is supported.
- Node.js 20 or newer for server-side rendering and build tools.
- Works with
importandrequire. TypeScript types included.
Related packages
consentbar comes in three packages. Install only the one that matches your project: react-consent-bar already includes consentbar, and next-consent-bar includes both.
| Package | Use it for |
|---|---|
| consentbar | Any website: plain HTML, WordPress, PHP, Vue, Svelte and more. The banner itself, plus consentbar/server to read consent on any server. |
| react-consent-bar (this package) | React apps (Vite, Create React App, Remix): hooks and components such as useConsent(), <ConsentGate> and <PrivacyChoicesButton>. |
| next-consent-bar | Next.js: everything in react-consent-bar, plus <ConsentScript> and reading consent on the server, so there is no banner flash. |
Also useful: crumbjar, typed cookies that can wait for consent before they are saved.
License
MIT
