react-cookie-consent

repository·master·Indexed 20 days ago

https://github.com/mastermindzh/react-cookie-consent

A small, simple, and customizable cookie consent bar for React applications. Version 10.0.2 provides a CookieConsent component with features including acceptance on scroll, page-obfuscating overlays, and customizable styling via inline styles or CSS classes. It includes utility functions like getCookieConsentValue and resetCookieConsentValue to manage consent status and supports advanced cookie configurations such as SameSite attributes and secure flags.

Tokens
8K
Snippets
23
Records
29
Agent score
68%

What's inside react-cookie-consent

  1. Understand the dual-cookie (Legacy) mechanism

    master

    To handle browsers that do not support the SameSite=None attribute, react-cookie-consent uses two cookies:

    1. Fallback Cookie: A cookie with a -legacy suffix is set first. This is designed to succeed on all browsers.
    2. Standard Cookie: The primary cookie is set second. This works on modern browsers but may fail on older ones.

    Checking Consent Logic: When the component checks for consent, it performs the check in reverse order:

    • It first checks for the regular cookie. If it exists, consent is granted.
    • If the regular cookie is missing, it checks for the legacy cookie. If that exists, consent is granted.
    • If neither exists, no consent has been given.
  2. Debug the CookieConsent component

    master

    Because the cookie consent bar is hidden once a user accepts it, you can use the debug={true} prop to keep the bar visible while evaluating styling changes.

    Note: Ensure you remove the debug property before deploying to production.

    <CookieConsent debug={true}></CookieConsent>
  3. Style the CookieConsent component

    master

    You can customize the appearance of the bar, the button, and the content using inline styles or CSS class names.

    Inline Styles

    Use the following props to apply inline styles. These will append to or replace the default styles:

    • style: Styles the main container (the bar).
    • buttonStyle: Styles the consent button.
    • contentStyle: Styles the text content area.

    CSS Class Names

    Alternatively, you can provide predefined CSS classes using these props:

    • containerClasses: Classes for the main container.
    • buttonClasses: Classes for the button.
    • contentClasses: Classes for the content area.

    Disabling Default Styles

    To remove all built-in styling and start from scratch, set disableStyles={true}.

    // Example: Changing bar background to red
    <CookieConsent style={{ background: "red" }}></CookieConsent>
    
    // Example: Changing button font-weight to bold
    <CookieConsent buttonStyle={{ fontWeight: "bold" }}></CookieConsent>
    
    // Example: Using predefined CSS classes (e.g., Bootstrap)
    <CookieConsent
      disableStyles={true}
      buttonClasses="btn btn-primary"
      containerClasses="alert alert-warning col-lg-12"
      contentClasses="text-capitalize"
    >
      This website uses cookies to enhance the user experience.
    </CookieConsent>
  4. Enable acceptance on scroll

    master

    You can automatically accept cookies when a user scrolls a certain percentage of the page. To use this, set:

    • acceptOnScroll: true
    • acceptOnScrollPercentage: A number representing the percentage of scroll required to trigger acceptance (e.g., 50).
    <CookieConsent
      acceptOnScroll
      acceptOnScrollPercentage={50}
      onAccept={() => console.log('Accepted via scroll')}
    >
      Scroll to accept cookies!
    </CookieConsent>
  5. Use the Overlay feature

    master

    The overlay prop generates a page-obfuscating overlay. This prevents users from interacting with the rest of the page until they interact with the cookie consent buttons.

    <CookieConsent location="bottom" cookieName="myAwesomeCookieName3" expires={999} overlay>
      This website uses cookies to enhance the user experience.
    </CookieConsent>
  6. Use the CookieConsent component

    master

    Import CookieConsent to render the consent bar anywhere in your React application. You can pass children to the component to define the message displayed to the user. You can also customize the appearance and behavior using props like location, buttonText, cookieName, style, buttonStyle, and expires.

    import CookieConsent from "react-cookie-consent";
    
    <CookieConsent
      location="bottom"
      buttonText="Sure man!!"
      cookieName="myAwesomeCookieName2"
      style={{ background: "#2B373B" }}
      buttonStyle={{ color: "#4e503b", fontSize: "13px" }}
      expires={150}
    >
      This website uses cookies to enhance the user experience.{" "}
      <span style={{ fontSize: "10px" }}>This bit of text is smaller :O</span>
    </CookieConsent>
  7. Enable Accept on Scroll

    master

    You can configure the cookie bar to disappear automatically after a user scrolls a specific percentage of the page. This behavior should be checked against local legislation (e.g., Italy) to ensure compliance.

    Use the following props:

    • acceptOnScroll: Set to true to enable this feature.
    • acceptOnScrollPercentage: The percentage of scroll required to trigger acceptance.
    • onAccept: A callback function that receives a boolean indicating if consent was given via scrolling.
    <CookieConsent
      acceptOnScroll={true}
      acceptOnScrollPercentage={50}
      onAccept={(byScroll) => {
        alert(`consent given. \n\n By scrolling? ${byScroll}`);
      }}
    >
      Hello scroller :)
    </CookieConsent>
  8. Handle cookie acceptance and decline events

    master

    Use the onAccept and onDecline props to execute logic when a user interacts with the consent bar.

    • onAccept: Receives an object with a boolean property acceptedByScrolling. This indicates if the user accepted by scrolling (if configured) or by clicking the button.
    • onDecline: Triggered when the user clicks the decline button. Note that you must include the enableDeclineButton prop for this to be available.
    // Handling acceptance
    <CookieConsent
      onAccept={(acceptedByScrolling) => {
        if (acceptedByScrolling) {
          alert("Accept was triggered by user scrolling");
        } else {
          alert("Accept was triggered by clicking the Accept button");
        }
      }}
    ></CookieConsent>
    
    // Handling decline
    <CookieConsent
      enableDeclineButton
      onDecline={() => {
        alert("nay!");
      }}
    ></CookieConsent>
  9. Configure extra cookie options

    master

    You can pass additional configuration options to the underlying cookie implementation using the extraCookieOptions prop. This is useful for setting properties like domain.

    <CookieConsent extraCookieOptions={{ domain: "myexample.com" }}>cookie bar</CookieConsent>
  10. Get the cookie consent value in your code

    master

    Use the getCookieConsentValue function to check the current status of the consent cookie in your application logic. You must provide the cookieName used by the component.

    import { getCookieConsentValue } from "react-cookie-consent";
    
    console.log(getCookieConsentValue("your_custom_cookie_name"));