Giter Site home page Giter Site logo

lukaskupczyk / react-hook-consent Goto Github PK

View Code? Open in Web Editor NEW
14.0 2.0 5.0 1.75 MB

React consent management solution for cookies and (external) scripts.

Home Page: https://lukaskupczyk.github.io/react-hook-consent/

License: MIT License

JavaScript 1.27% TypeScript 85.95% SCSS 12.78%
consent consent-management hook hooks react react-hooks typescript

react-hook-consent's Introduction

publish workflow Test Coverage npm version MIT License

react-hook-consent

React consent management solution and banner for cookies, local storage, session storage and (external) scripts.

react-hook-consent Screenshot

Demo

Check out the CodeSandbox for a working example.

Documentation

Features

  • Provides the consent context to components
  • Loads (external) scripts based on consent state
  • Deletes cookies, local storage and session storage when consent declined
  • Hook to retrieve and change the current consent
  • Optional Banner with detailed settings to approve / decline consent
  • Persists the selection to local storage
  • Ready for Next.js
  • Dark and light mode
  • Styling via css

Installation

yarn add react-hook-consent

# or

npm install react-hook-consent

Basic usage

Wrap the application in the ConsentProvider. Provide settings via the options prop. Optionally use the ConsentBanner component to display a consent banner to the user.

/*
 * index.tsx
 */

import { ConsentBanner, ConsentProvider } from 'react-hook-consent';

// styling
import 'react-hook-consent/dist/styles/style.css';

// ...
<ConsentProvider
    options={{
        services: [
            {
                id: 'myid',
                name: 'MyName',
                scripts: [
                    { id: 'external-script', src: 'https://myscript.com/script.js' },
                    { id: 'inline-code', code: `alert("I am a JavaScript code");` },
                ],
                cookies: [{ pattern: 'cookie-name' }, { pattern: /regex/ }],
                localStorage: ['local-storage-key'],
                sessionStorage: ['session-storage-key'],
                mandatory: true,
            },
        ],
        // customHash: 'my-custom-hash', // optional, e.g. when changing the options based on language
        theme: 'light',
    }}
>
    <App />
    <ConsentBanner
        settings={{ hidden: false, label: 'More', modal: { title: 'Modal title' } }}
        decline={{ hidden: false, label: 'No' }}
        approve={{ label: 'Yes' }}
    >
        <>
            Can we use cookies and external services according to our <a href="test">privacy policy</a> to improve the
            browsing experience?
        </>
    </ConsentBanner>
</ConsentProvider>;
// ...

react-hook-consent's People

Contributors

cachho avatar lukaskupczyk avatar timhagn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-hook-consent's Issues

[BUG] Cookie deletion does not work

Hey, somehow I cannot get the cookies to be deleted if I revoke the consent later.

import type { ConsentOptions } from 'react-hook-consent';

const scriptMatomo = `
  var _paq = window._paq = window._paq || [];
  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//matomo.domaincom/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
`;

export const consentProviderOptions: ConsentOptions = {
  services: [
    {
      id: 'matomo',
      name: 'Matomo Analytics',
      description:
        'Analytics hosted on our own server. A privacy respecting alternative to Google Analytics.',
      scripts: [{ id: 'inline-code', code: scriptMatomo }],
      cookies: [
        { pattern: '_pk_ref.*' },
        { pattern: '_pk_cvar.*' },
        { pattern: '_pk_id.*' },
        { pattern: '_pk_ses.*' },
        { pattern: 'mtm_consent.*' },
        { pattern: 'mtm_consent_removed.*' },
        { pattern: 'mtm_cookie_consent.*' },
        { pattern: 'matomo_ignore.*' },
        { pattern: 'matomo_sessid.*' },
        { pattern: '_pk_hsr.*' },
      ],
      // localStorage: ['local-storage-key'],
      // sessionStorage: ['session-storage-key'],
      mandatory: false,
    },
  ],
  theme: 'dark',
};

The cookies

_pk_id.1.1fff:"69bbccaf910e190e.1703006272."
_pk_ses.1.1fff:"1"

still exist.

I test by accepting the cookies, deleting the react-hook-consent from local storage, refreshing and this time declining the cookies. The consent array in local storage is empty, so I'm guessing my test setup works (I'm using the demo example).

I tried to use the regex constructor too, to make sure the pattern is interpreted as a regular expression:

      cookies: [
        { pattern: new RegExp('_pk_ref.*') },
        { pattern: new RegExp('_pk_cvar.*') },
        { pattern: new RegExp('_pk_id.*') },
        { pattern: new RegExp('_pk_ses.*') },
        { pattern: new RegExp('mtm_consent.*') },
        { pattern: new RegExp('mtm_consent_removed.*') },
        { pattern: new RegExp('mtm_cookie_consent.*') },
        { pattern: new RegExp('matomo_ignore.*') },
        { pattern: new RegExp('matomo_sessid.*') },
        { pattern: new RegExp('_pk_hsr.*') },
      ],

same result.

[BUG] Has consent not working

Has consent returns true, when the consent array is empty.

  const { hasConsent, consent } = useConsent();

  useEffect(() => {
    console.log(consent);
    console.log(hasConsent('user-preferences'));
}, []);
Array [] UserPreferencesProvider.tsx:15:12](webpack://_N_E/src/utils/providers/UserPreferencesProvider.tsx?a62e)
true [UserPreferencesProvider.tsx:16:12](webpack://_N_E/src/utils/providers/UserPreferencesProvider.tsx?a62e)

Local storage was cleared right before thi.

Consent Options Hash Issue

Our consent options depend on the language of the site and whenever a user switches to another language the cookie banner appears again.

Therefore the hash calculation should not relay on any user texts. Using the cookie names should be sufficient.

feature request: consent for local storage

You need consent for local storage, just like you do for cookies. In the readme I couldn't find that you could ask for permission for local storage.

I guess I could just add a cookie for each local storage key, but I think this would be a need feature.

What do you think?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.