# Cookiefirst - official React component

Our React helper component for [react cookie consent](https://cookiefirst.com/react-cookie-consent/), built with integration capabilities from CookieFirst, provides a comprehensive solution for managing user consent on your React website. This component helps ensure compliance with international privacy laws such as GDPR, ePrivacy, LGPD, and CCPA by allowing visitors to give or change their consent for cookies and third-party scripts used on your site. CookieFirst is a Google Certified CMP offering the [Google Consent Mode v2](https://cookiefirst.com/google-consent-mode-v2-released/) integration.

### Key Features:

1.  **Automated Cookie Consent**: Automatically manages cookie consent based on user preferences.
2.  **Periodic Cookie Scans**: Regularly scans and updates your site's cookie usage to ensure ongoing compliance.
3.  **Customizable Cookie Banner**: Easily add and customize a cookie consent banner to your site, ensuring a seamless user experience.
4.  **Consent Management**: Includes options for users to manage their cookie preferences directly through the banner.
5.  **Integration with Google Tag Manager**: Compatible with Google Tag Manager and Google Consent Mode, making it easy to manage third-party scripts based on user consent.
6.  **Multilingual Support**: Generates automated cookie policies in over 40 languages, catering to a global audience.

# Contact

If you have any questions or want to report a problem, contact us at [https://support.cookiefirst.com/hc/en-us/requests/new](https://support.cookiefirst.com/hc/en-us/requests/new)

# Latest Changes

- Added a more specific return type to 'useCookieFirst'
- Children will now be rendered if the banner fails to load or fails to authenticate

# Table of contents

- [Installation](#installation)
- [Usage](#usage)
- [Example](#example)
- [List of properties](#list-of-properties)
- [Properties](#properties)

# Installation

**npm**

    npm i @cookiefirst/cookiefirst-react

**yarn**

    yarn add @cookiefirst/cookiefirst-react

## Usage

```javascript
import { ReactCookieFirst } from '@cookiefirst/cookiefirst-react'

<ReactCookieFirst  url="URL_FROM_ADMIN_PANEL/consent.js">
	{... rest of your app}
</ReactCookieFirst>
```

You can find your url by logging to https://app.cookiefirst.com/

- navigate to 'domains' from the menu

![domains link](https://consent.cookiefirst.com/npm/npm2.png)

- in list of domains select 'settings' for the domain you want connect

![domain settings](https://consent.cookiefirst.com/npm/npm3.png)

- navigate to 'your embed script' from the menu

![embed script link](https://consent.cookiefirst.com/npm/npm4.png)

- copy **just the url** from the embed script

![embed script](https://consent.cookiefirst.com/npm/npm6.png)

## Example

```javascript
import { useCookieFirst } from '@cookiefirst/cookiefirst-react';

const ExampleComponent = () => {
  const { TCFgvl, TCFacceptCategory } = useCookieFirst();

  useEffect(() => {
    if (TCFgvl) {
      TCFacceptCategory([
        ['purposes', 2],
        ['purposes', 1],
        ['purposes', 4],
        ['purposes', 6],
      ]);
    }
  }, [TCFgvl]);
};
```

## List of properties

#### Cookie Preference Center

- [openPanel()](#openpanelname)
- [closePanel()](#closepanel)

#### Integration settings

- [stealthMode](#stealthmode)
- [changeLanguage()](#changelanguagelang)

#### Consent properties

- [consent](#consent)
- [acceptedServices](#acceptedServices)
- [updateConsent()](#updateconsentconsent-tcfconsent)
- [withdrawConsent()](#withdrawconsent)
- [consentTimestamp](#consenttimestamp)
- [acceptCategory()](#acceptcategorycategorynamenames)
- [declineCategory()](#declinecategorycategorynamenames)
- [acceptService()](#acceptserviceserviceservices)
- [declineService()](#declineserviceserviceservices)
- [acceptAllCategories()](#acceptallcategories)
- [acceptPreselectedCategories()](#acceptpreselectedcategories)
- [deny()](#deny)
- [declineAllCategories()](#declineallcategories)

#### TCF and TCF Consent

**_NOTE:
Functions and properties below require TCF enabled in admin panel._**

- [TCFconsent](#tcfconsent)
- [updateConsent()](#updateconsentconsent-tcfconsent)
- [TCFisEnabled](#tcfisenabled)
- [TCFeventStatus](#tcfeventstatus)
- [TCFcountry](#tcfcountry)
- [TCFgvl](#tcfgvl)
- [TCFgatp](#tcfgatp)
- [TCFgetConsentStructure()](#tcfgetconsentstructure)
- [TCFacceptCategory()](#tcfacceptcategorycategorycategories)
- [TCFdeclineCategory()](#tcfdeclinecategorycategorycategories)
- [TCFacceptCategoryLegitimateInterest()](#tcfacceptcategorylegitimateinterestcategorycategories)
- [TCFdeclineCategoryLegitimateInterest()](#tcfdeclinecategorylegitimateinterestcategorycategories)
- [TCFacceptVendor()](#tcfacceptvendorvendorvendors)
- [TCFdeclineVendor()](#tcfdeclinevendorvendorvendors)
- [TCFacceptVendorLegitimateInterest()](#tcfacceptvendorlegitimateinterestvendorvendors)
- [TCFdeclineVendorLegitimateInterest()](#tcfdeclinevendorlegitimateinterestvendorvendors)
- [TCFisVendorAccepted()](#tcfisvendoracceptedvendorid)
- [TCFisVendorLegitimateInterestAccepted()](#tcfisvendorlegitimateinterestacceptedvendorid)
- [TCFisCategoryAccepted()](#tcfiscategoryacceptedname-id)
- [TCFisCategoryLegitimateInterestAccepted()](#tcfiscategorylegitimateinterestacceptedname-id)
- [TCFacceptGatpVendor()](#tcfacceptgatpvendorvendorvendors)
- [TCFdeclineGatpVendor()](#tcfdeclinegatpvendorvendorvendors)
- [TCFisGatpVendorAccepted()](#tcfisgatpvendoracceptedid)

#### Uncategorized

- [visitorId](#visitorid)
- [renderEmbeds()](#renderembeds)
- [fetchLatestScan()](#fetchlatestscan)
- [notifyViewChanged()](#notifyviewchanged)

## Properties

### openPanel(name?)

Opens the Cookie Preference Center if not currently open.

---

- **"name"** _(optional)_: string - name of the tab which should be made active when the Preference Center open.

  Possible values:

  - "settings",
  - "cookies",
  - "policy"

---

```javascript
const { openPanel } = useCookieFirst();

// open the Settings tab by default
openPanel();

// open the specified tab
openPanel('cookies');
```

---

### closePanel()

Closes the Cookie Preference Center if it's open.
Will throw an Error in Stealth Mode.

```javascript
const { closePanel } = useCookieFirst();

closePanel();
```

---

### stealthMode

When in Stealth Mode, CookieFirst Banner doesn't render any consent-management interface. The only rendered content is the cookie declaration on a page supporting it.

---

### changeLanguage(lang)

This function allows developers to switch banner language.

**Note:** for languages we are using 2-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) codes. For example: `en` and not `en-GB`

- **"lang"**: string -2-letter code for new language.

---

### consent

Get info about the accepted categories.
If you want to get info about accepted services go to [acceptedServices](#acceptedservices)

If consent is available, it will be an object of this structure:

```javascript
{
	necessary: true, // necessary category can't be disabled
	performance: true|false,
	functional: true|false,
	advertising: true|false,
}
```

otherwise it will be empty.

```javascript
acceptedCategories === null; // true
```

---

### acceptedServices

Get info about the accepted services.

If consent is available, acceptedServices will be an object where keys are the unique scripts identifiers configured in Third party scripts section of our admin panel and values are true or false depending of acceptance status of each service of this structure:

```javascript
{
	unique_script_id: true|false,
	other_script_id: true|false,
}
```

otherwise it will be empty.

```javascript
acceptedServices === null; // true
```

---

### updateConsent(consent, tcfConsent?)

This function allows developers to update visitor's consent and set it to a given value.

---

- **"consent"** : object - object with information about new consent.

```javascript
const { updateConsent } = useCookieFirst();

const newConsent = {
  necessary: true, // necessary category can't be disabled
  performance: true | false,
  functional: true | false,
  advertising: true | false,
};

CookieFirst.updateConsent(newConsent);

// or to update existing

const { updateConsent, consent } = useCookieFirst();

const newConsent = { ...consent };
newConsent.functional = true;
CookieFirst.updateConsent(newConsent);
```

---

\*_TCF have to be enabled in admin panel in order to use this_

- **"tcfConsent"** _(optional)_: object - object with information about new tcf consent. Since tcf consent have very deep and detailed structure to create completely new consent you can use helper function [TCFgetConsentStructure](#TCFgetConsentStructure)

```javascript
const { consent, updateConsent, TCFconsent } = useCookieFirst();

const newConsentTCF = { ...TCFgetConsentStructure() };
newConsentTCF.vendors = { 1: true, 5: true, 10: true };

updateConsent(consent, newConsentTCF);

// or to update existing
const { consent, updateConsent, TCFconsent } = useCookieFirst();

const newConsentTCF = { ...TCFconsent };
newConsentTCF.vendors[5] = true;
updateConsent(consent, newConsentTCF);
```

---

### withdrawConsent()

Consent withdraw function will clear the visitor's consent and log such change in our consent log. After this action is performed, website will reload to allow visitor's to have a fresh start on a domain. Banner will be shown again and no methods changing consent will be available until visitor consents again.

```javascript
const { withdrawConsent } = useCookieFirst();

withdrawConsent();
```

---

### consentTimestamp

Time in ms when user consented.

```javascript
const { consentTimestamp } = useCookieFirst();
```

---

### acceptCategory(categoryName/names)

This function allows developers to accept single or multiple categories

---

- **"categoryName"**: string or array of strings - name/names of the categories that developer want

  Possible values:

  - "necessary",
  - "performance",
  - "functional",
  - "advertising"

```javascript
const { acceptCategory } = useCookieFirst();

acceptCategory('functional');

// or with multiple

acceptCategory(['functional', 'advertising']);
```

---

### declineCategory(categoryName/names)

This function allows developers to decline single or multiple categories

---

- **"categoryName"**: string or array of strings - name/names of the categories that developer want

  Possible values:

  - "performance",
  - "functional",
  - "advertising"

```javascript
const { declineCategory } = useCookieFirst();

declineCategory('functional');

// or with multiple

declineCategory(['functional', 'advertising']);
```

---

### acceptService(service/services)

This function allows developers to accept specified services by their unique identifier. If consent policy option is set to "category-based" and not "service-based", the function will accept all categories of which this service is part.

---

- **"service"**: string or array of strings - unique id of service/services that should be accepted.

```javascript
const { acceptService } = useCookieFirst();

acceptService('service_id');

// or with multiple

acceptService(['service_id_1', 'service_id_2']);
```

---

### declineService(service/services)

This function allows developers to decline specified services by their unique identifier. If consent policy option is set to "category-based" and not "service-based", the function will decline all categories of which this service is part.

---

- **"service"**: string or array of strings - unique id of service/services that should be declined.

```javascript
const { declineService } = useCookieFirst();

declineService('service_id');

// or with multiple

declineService(['service_id_1', 'service_id_2']);
```

---

### acceptAllCategories()

This function allows developers to consent to all available categories of cookies.

```javascript
const { acceptAllCategories } = useCookieFirst();

acceptAllCategories();
```

---

### acceptPreselectedCategories()

This function allows developers to accept only the categories, which have been previously pre-selected in the domain settings screen in CookieFirst admin panel.

```javascript
const { acceptPreselectedCategories } = useCookieFirst();

acceptPreselectedCategories();
```

---

### deny()

This function allows developers to deny the consent completely.

```javascript
const { deny } = useCookieFirst();

deny();
```

---

### declineAllCategories()

This function allows developers to accept only the necessary category and decline all other categories, with one line of code. Although it may seem similar to the [withdrawConsent](#withdrawConsent) function, it doesn't erase the consent completely and doesn't show the cookie banner. It updates the consent to have only the necessary cookies enabled.

```javascript
const { declineAllCategories } = useCookieFirst();

declineAllCategories();
```

---

**_NOTE: Functions and properties below require TCF enabled in admin panel._**

### TCFconsent

Get info about current TCF consent.

If consent is available, it will be an object of this structure:

```javascript
{
	vendors: {},
	categories: {},
	vendorsLegitimateInterest: {},
	categoriesLegitimateInterest: {},
	gatp: {}
}
```

otherwise it will be empty.

```javascript
const { TCFconsent } = useCookieFirst();

TCFconsent === null; // true
```

---

### TCFisEnabled

Information if TCF has been enabled in admin panel.

```javascript
const { TCFisEnabled } = useCookieFirst();
```

---

### TCFeventStatus

Current state of banner regarding TCF integration.

Possible values:

- tcloaded,
- cmpuishown,
- useractioncomplete

You can read more about eventStatus in official IAB documentation: [here](https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20CMP%20API%20v2.md#addeventlistener)

```javascript
const { TCFeventStatus } = useCookieFirst();
```

---

### TCFcountry

Country code of the country that determines the legislation of reference.

```javascript
const { TCFcountry } = useCookieFirst();
```

---

### TCFgvl

Current Global Vendor List (GVL) that contains information about all registered and approved Vendors, Purposes, Features, Special Purposes, Special Features, Stacks and Data Categories.

You can read more about GVL [here](https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20Consent%20string%20and%20vendor%20list%20formats%20v2.md#the-global-vendor-list) and check current GVL [here](https://vendor-list.consensu.org/v3/purposes-en.json)

**NOTE:**
**GVL is required to perform any action regarding TCF consent, so be sure to check if it has been already downloaded before you try to perform any action regarding consent.**

```javascript
const { TCFgvl, TCFacceptCategory } = useCookieFirst();

if (TCFgvl) {
  TCFacceptCategory([
    ['purposes', 1],
    ['purposes', 3],
    ['purposes', 4],
    ['purposes', 6],
  ]);
}
```

---

### TCFgatp

Current Google's Ad Tech Providers (ATP) list that contains information about all Ad technology providers that are part of a commonly used list.

You can read more about Google ATP [here](https://support.google.com/admanager/answer/9012903?sjid=3292287987943508236-EU)

**NOTE:**
**Google ATP is required to perform any action regarding Google ATP consent, so be sure to check if it has been already downloaded before.**

```javascript
const { TCFgatp, TCFacceptGatpVendor } = useCookieFirst();

if (TCFgatp) {
  TCFacceptGatpVendor([2, 7, 10]);
}
```

---

### TCFgetConsentStructure()

This function allows developers to get empty structure of TCF consent, very useful if you want to prepare and update entire consent at once by using function [updateConsent()](#updateConsent)

Example empty structure has been shown [here](#TCFconsent)

---

### TCFacceptCategory(category/categories)

This function allows developers to accept given category or list of categories.

- **"category"**: array/array of arrays - single category consist of name of category type and number of specific category.

  Possible values for type:

  - "purposes",
  - "specialPurposes",
  - "specialFeatures",
  - "features"

```javascript
const { TCFgvl, TCFacceptCategory } = useCookieFirst();

// single category
if (TCFgvl) {
  TCFacceptCategory(['purposes', 2]);
}

// or with multiple

if (TCFgvl) {
  TCFacceptCategory([
    ['purposes', 1],
    ['purposes', 3],
    ['purposes', 4],
    ['purposes', 6],
  ]);
}
```

---

### TCFdeclineCategory(category/categories)

This function allows developers to decline given category or list of categories.

- **"category"**: array/array of arrays - single category consist of name of category type and number of specific category.

  Possible values for type:

  - "purposes",
  - "specialPurposes",
  - "specialFeatures",
  - "features"

```javascript
const { TCFgvl, TCFdeclineCategory } = useCookieFirst();

// single category
if (TCFgvl) {
  TCFdeclineCategory(['purposes', 2]);
}

// or with multiple

if (TCFgvl) {
  TCFdeclineCategory([
    ['purposes', 1],
    ['purposes', 3],
    ['purposes', 4],
    ['purposes', 6],
  ]);
}
```

---

### TCFacceptCategoryLegitimateInterest(category/categories)

This function allows developers to accept given legitimate interest category or list of legitimate interest categories.

- **"category"**: array/array of arrays - single category consist of name of category type and number of specific category.

  Possible values for type:

  - "purposes"

```javascript
const { TCFgvl, TCFacceptCategoryLegitimateInterest } = useCookieFirst();

// single category
if (TCFgvl) {
  TCFacceptCategoryLegitimateInterest(['purposes', 2]);
}

// or with multiple

if (TCFgvl) {
  TCFacceptCategoryLegitimateInterest([
    ['purposes', 2],
    ['purposes', 7],
    ['purposes', 8],
  ]);
}
```

---

### TCFdeclineCategoryLegitimateInterest(category/categories)

This function allows developers to decline given legitimate interest category or list of legitimate interest categories.

- **"category"**: array/array of arrays - single category consist of name of category type and number of specific category.

  Possible values for type:

  - "purposes",

```javascript
const { TCFgvl, TCFdeclineCategoryLegitimateInterest } = useCookieFirst();

// single category
if (TCFgvl) {
  TCFdeclineCategoryLegitimateInterest(['purposes', 2]);
}

// or with multiple

if (TCFgvl) {
  TCFdeclineCategoryLegitimateInterest([
    ['purposes', 2],
    ['purposes', 7],
    ['purposes', 8],
  ]);
}
```

---

### TCFacceptVendor(vendor/vendors)

This function allows developers to accept given vendor or list of vendors

- **"vendor"**: number/array of numbers - unique id of vendor/vendors that should be accepted.

```javascript
const { TCFgvl, TCFacceptVendor } = useCookieFirst();

// single vendor
if (TCFgvl) {
  TCFacceptVendor(10);
}

// or with multiple
if (TCFgvl) {
  TCFacceptVendor([2, 6, 10, 30]);
}
```

---

### TCFdeclineVendor(vendor/vendors)

This function allows developers to decline given vendor or list of vendors

- **"vendor"**: number/array of numbers - unique id of vendor/vendors that should be declined.

```javascript
const { TCFgvl, TCFdeclineVendor } = useCookieFirst();

// single vendor
if (TCFgvl) {
  TCFdeclineVendor(10);
}

// or with multiple
if (TCFgvl) {
  TCFdeclineVendor([2, 6, 10, 30]);
}
```

---

### TCFacceptVendorLegitimateInterest(vendor/vendors)

This function allows developers to accept legitimate interest for given vendor or list of vendors

- **"vendor"**: number/array of numbers - unique id of vendor/vendors that should be accepted.

```javascript
const { TCFgvl, TCFacceptVendorLegitimateInterest } = useCookieFirst();

// single vendor
if (TCFgvl) {
  TCFacceptVendorLegitimateInterest(8);
}

// or with multiple
if (TCFgvl) {
  TCFacceptVendorLegitimateInterest([8, 11, 15]);
}
```

---

### TCFdeclineVendorLegitimateInterest(vendor/vendors)

This function allows developers to decline legitimate interest for given vendor or list of vendors

- **"vendor"**: number/array of numbers - unique id of vendor/vendors that should be declined.

```javascript
const { TCFgvl, TCFdeclineVendorLegitimateInterest } = useCookieFirst();

// single vendor
if (TCFgvl) {
  TCFdeclineVendorLegitimateInterest(8);
}

// or with multiple
if (TCFgvl) {
  TCFdeclineVendorLegitimateInterest([8, 11, 15]);
}
```

---

### TCFisVendorAccepted(vendorID)

This function allows developers to check if vendor with given ID has been accepted by user.

- **"vendorID"**: number- unique id of vendor

```javascript
const { TCFisVendorAccepted } = useCookieFirst();

TCFisVendorAccepted(10); //false or true
```

---

### TCFisVendorLegitimateInterestAccepted(vendorID)

This function allows developers to check if legitimate interest for vendor with given ID has been accepted by user.

- **"vendorID"**: number- unique id of vendor

```javascript
const { TCFisVendorLegitimateInterestAccepted } = useCookieFirst();

TCFisVendorLegitimateInterestAccepted(8); //false or true
```

---

### TCFisCategoryAccepted(name, id)

This function allows developers to check if category with given category type and id has been accepted

- **"name"**: string - name of category type
  possible values:
  - purposes,
  - specialPurposes,
  - specialFeatures
  - features
- **"id"**: number - id of category in given type

```javascript
const { TCFisCategoryAccepted } = useCookieFirst();

TCFisCategoryAccepted('specialPurposes', 2); //false or true
```

---

### TCFisCategoryLegitimateInterestAccepted(name, id)

This function allows developers to check if legitimate interest for category with given category type and id has been accepted

- **"name"**: string - name of category type
  possible values:

  - purposes,

- **"id"**: number - id of category in given type

```javascript
const { TCFisCategoryLegitimateInterestAccepted } = useCookieFirst();

TCFisCategoryLegitimateInterestAccepted('purposes', 8); //false or true
```

---

---

### TCFacceptGatpVendor(vendor/vendors)

This function allows developers to accept GATP vendor or list of GATP vendors

- **"vendor"**: number/array of numbers - unique id of GATP vendor/vendors that should be accepted.

```javascript
const { TCFgatp, TCFacceptGatpVendor } = useCookieFirst();

// single vendor
if (TCFgatp) {
  TCFacceptGatpVendor(2);
}

// or with multiple
if (TCFgatp) {
  TCFacceptGatpVendor([2, 7, 10]);
}
```

---

### TCFdeclineGatpVendor(vendor/vendors)

This function allows developers to decline GATP vendor or list of GATP vendors

- **"vendor"**: number/array of numbers - unique id of GATP vendor/vendors that should be declined.

```javascript
const { TCFgatp, TCFdeclineGatpVendor } = useCookieFirst();

// single vendor
if (TCFgatp) {
  TCFdeclineGatpVendor(2);
}

// or with multiple
if (TCFgatp) {
  TCFdeclineGatpVendor([2, 7, 10]);
}
```

---

### TCFisGatpVendorAccepted(id)

This function allows developers to check if GATP vendor with given d has been accepted

- **"id"**: number - unique id of gatp vendor

```javascript
const { TCFisGatpVendorAccepted } = useCookieFirst();

TCFisGatpVendorAccepted(2); //false or true
```

---

### visitorId

Unique id, used to link user's consents. Useful when user contact with request to revoke/reset it.

```javascript
const { visitorId } = useCookieFirst();
```

---

### renderEmbeds()

The JS API allows you to force the rendering of embedded contents (like the cookie policy or cookie table). This in integrations where the container div for the embeds is not available at the moment our banner loads. This might be the case if you dynamically add it to the DOM via single page app view navigation or just by simple JS code. After the div is added to the DOM, run `renderEmbeds()` to place the embedded content inside of it.

---

### fetchLatestScan()

The JS API allows you to get the list of cookies found on your website together with the latest scan date. To do this, use the method. It will return a promise which resolves to the following response:

```javascript
{
  updated_at: "2020-10-29T13:30:23+00:00", // latest scan date and time in ISO 8601
  formatcookies: [], // an array of cookies found on your site together with any custom cookies you may have added as well as our own cookies needed for banner to work
}
```

---

### notifyViewChanged()

That function is intended for SPA. To let the banner know that page might have changed, new listeners appeared or user navigated to new subpage.

---
