Skip to content
Advertisement

Google Consent Mode Implementation using Gatsby

I am following this tutorial about implementing google consent mode to add cookies to my website ! By using Gatsby.js I am not sure how to add these codes :

<!-- The initial config of Consent Mode -->
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('consent', 'default', {
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 1500,
});
gtag('set', 'ads_data_redaction', true);
</script>
​
<!-- Cookie Information Pop-up Script is required for the SDK -->
<script id="CookieConsent" src="https://policy.app.cookieinformation.com/uc.js" data-culture="EN" type="text/javascript"></script>
​
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING-ID"></script>
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
​
gtag('config', 'TRACKING-ID');
</script>
​
</head>
<body>

Do you have any idea how to implement this code in Gatsby , is there any library or something that will help to implement these scripts ! Thanks

Advertisement

Answer

This component is used as the initial screen that applies when the page loads.

import React, { useState, useEffect } from 'react';

import { useLocation } from '@reach/router';
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies';
import Cookies from 'js-cookie';

import CookieSettings from './Settings';

const CookieBanner = () => {
    const [showBanner, setShowBanner] = useState(false);
    const [showSettings, setShowSettings] = useState(false);
    const location = useLocation();

    // showSettings -> use this state property to open a configuration
    // window which may open up more information on the cookie(s) being applied

    useEffect(() => {
        setShowBanner(Cookies.get('gatsby-gdpr-responded') !== 'true');
    }, [])

    useEffect(() => {
        initTracking();
    }, [Cookies.get('gatsby-gdpr-responded')])

    const initTracking = () => {
        initializeAndTrack(location)
    }

    const handleAccept = () => {
        Cookies.set('gatsby-gdpr-google-analytics', true, { expires: 365 })
        handleCloseAll();
    }

    const handleDecline = () => {
        Cookies.remove('gatsby-gdpr-google-analytics');
        handleCloseAll();
    }

    const handleCloseAll = () => {
        setShowSettings(false);
        setShowBanner(false);

        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });
    }

    return (
        // add your component logic here
        // Take not of the different functions that are available above, like handleAccept / handleDecline / handleCloseAll 
        // handleCloseAll -> if a user declines / closes the banner
        // handleAccept -> a button to accept by default
        // handleDecline -> a button to decline the cookies

    )
}

export default CookieBanner

The next component is more of a Configuration screen, which provides more information on the cookies being applied, if you take note on the import of Toggle, we use a toggle to allow users to specifically toggle on or off their cookies at any point, you of course if you have many GDPR compliances, may want to either create separate functions that handle the removal of cookies or a reusable function that is passed the name of the cookie to be removed / applied.

import React, { useState } from 'react';

import Cookies from 'js-cookie';

import Button from '@components/Button';
import Toggle from '@components/Inputs/Toggle';

const CookieSettings = ({
    handleAccept,
    handleDecline,
    initTracking,
    handleCloseAll
}) => {
    const [trackAnalytics, setTrackAnalytics] = useState(Cookies.get('gatsby-gdpr-google-analytics') === 'true')

    const handleToggle = () => {
        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });

        setTrackAnalytics((prevState) => {
            if (prevState) {
                Cookies.remove('gatsby-gdpr-google-analytics');
            } else {
                Cookies.set('gatsby-gdpr-google-analytics', true, { expires: 365 })
            }

            return !prevState
        })

        initTracking();
    }

    return (
        // your JSX code here
    )
}

export default CookieSettings;

EDIT

// A some what reusable function that you can pass a cookie name too and switch over the name provided and set the required cookie.
const handleToggle = (cookieName) => {
        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });

        switch (cookieName) {
            case 'gatsby-gdpr-google-analytics':
                return setTrackAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            case 'gatsby-gdpr-google-tagmanager':
                return setTagAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            case 'gatsby-gdpr-facebook-pixel':
                return setFacebookAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            default:
                break;
        }

        initTracking()
    }

// A JSX toggle within your cookie setting
<Toggle active={trackAnalytics} toggleActive={() => handleToggle('gatsby-gdpr-google-analytics')} />
// The toggle component itself
import React from 'react';
import cx from 'classnames'
import PropTypes from 'prop-types'
import './styles.scss';

export default function Toggle({
    active = false,
    toggleActive,
}) {

    return (
        <div onClick={typeof toggleActive === 'function' && toggleActive} className={cx('toggle relative cursor-pointer', { active })} />
    )
}


Toggle.propTypes = {
    active: PropTypes.bool,
    toggleActive: PropTypes.func.isRequired
}

Toggle.defaultProps = {
    active: false,
}

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement