meg
meg

Reputation: 51

How to persist cookies consent choices with react-cookie-consent?

I have created a cookie banner but I do not know how to make the cookies chosen by the user to persist and be available to access on every page. I would also want to execute the script from Google Analitycis if the user accepted the analytics cookies. Can anyone help me please? I have placed the code from _app.js below:

import TopNav from "../components/TopNav";
import "bootstrap/dist/css/bootstrap.min.css";
import "antd/dist/antd.css";
import "../public/css/styles.css";
import {useState, useEffect} from "react";
import {useRouter} from "next/router";
import * as gtag from '../lib/gtag';
import Head from "next/head";
import CookieConsent, {getCookieConsentValue} from "react-cookie-consent";

const App = ({ Component, pageProps }) => {
  const router = useRouter()

  const cookieConsent = getCookieConsentValue();

  const [checkedOne, setCheckedOne] = useState(false);
  const [checkedTwo, setCheckedTwo] = useState(false);

  const handleChangeOne = () => {
    setCheckedOne(!checkedOne);
  };

  const handleChangeTwo = () => {
    setCheckedTwo(!checkedTwo);
  };

  const [necessaryConsent, updateNecessaryConsent] = useState("denied");
  const [analyticsConsent, updateAnalyticsConsent] = useState("denied");
  const [marketingConsent, updateMarketingConsent] = useState("denied");


  return (
    <>
      {/* Global Site Tag (gtag.js) - Google Analytics */}
      <Head>
      <script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
      />
      <script
        id="gtag-init"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${gtag.GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />
      </Head>
      {/* saves the user's response */}
    <CookieConsent
        enableDeclineButton
        onDecline={() => {
          updateNecessaryConsent("denied");
          updateAnalyticsConsent("denied");
          updateMarketingConsent("denied"); 
        }}
        onAccept={() => {
          updateNecessaryConsent("granted");
          if (checkedOne === true) {
            console.log('YAY')
            updateAnalyticsConsent("granted");
          }
          if (checkedTwo === true) {
            updateMarketingConsent("granted");
          }
        }}
        buttonText="Accept Selected"
        declineButtonText="Decline"
        ariaAcceptLabel="Accept cookies"
        ariaDeclineLabel="Decline cookies"
        expires={150}
      >
        We use cookies to enhance the user experience and analyze site traffic.
        For more information please read our{" "}
        <a href="/privacy-policy">privacy policy.</a>
        <div>You can decide which cookies are used by selecting the respective options below. 
          Please note that your selection may impair in the functionality of the service.</div>
      <div>
      <label>
        <input
          type="checkbox"
          disabled
          checked
        />
        {" "}Technically necessary cookies: Enable you to navigate and use the basic functions and to store preferences.
      </label>
      </div> 
      <div>
      <Checkbox
        label="    Analysis cookies: Enable us to determine how visitors interact with our service in order to improve the user experience."
        value={checkedOne}
        onChange={handleChangeOne}
      />
      </div>
      <div>
      <Checkbox
        label="    Marketing cookies: Enable us to offer and evaluate relevant content and interest-based advertising."
        value={checkedTwo}
        onChange={handleChangeTwo}
      />
      </div> 
      </CookieConsent>
      <TopNav />
      <Component {...pageProps} />
    </>
  )
}

export default App;

const Checkbox = ({ label, value, onChange }) => {
  return (
    <label>
      <input type="checkbox" checked={value} onChange={onChange} />
      {label}
    </label>
  );
};

Upvotes: 5

Views: 4528

Answers (1)

Webber
Webber

Reputation: 5484

You have to set cookieName prop as suggested in the docs from react-cookie-consent.

Upvotes: 1

Related Questions