Skip to content

Instantly share code, notes, and snippets.

@secretorange
Last active August 20, 2022 05:29
Show Gist options
  • Save secretorange/64c766062e6540302d1c8fb714222d6d to your computer and use it in GitHub Desktop.
Save secretorange/64c766062e6540302d1c8fb714222d6d to your computer and use it in GitHub Desktop.
Simple Cookie Consent banner in React without dependencies.
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { getCookie, setCookie } from './utils';
export default function CookieConsent(){
const [consent, setConsent] = useState(false);
useEffect(() => {
const consent = getCookie("consent");
if(consent){
setConsent(true);
}
}, [])
const onCookieAcceptClick = () => {
setCookie("consent", "yes", 365);
setConsent(true);
};
if(consent){
return null;
}
return (
<div className='bg-orange p-5 flex flex-col justify-center items-center fixed bottom-0 left-0 right-0 text-white'>
<p>This website uses cookies to improve your experience.</p>
<p>By continuing to browse the site, you are agreeing to our use of cookies and tracking tools.</p>
<div className="flex gap-5 items-center mt-2.5">
<button className="btn bg-black" onClick={onCookieAcceptClick}>Accept</button>
<Link to="/misc/cookies" className="font-bold">Read More</Link>
</div>
</div>
);
}
export function setCookie(cname: string, cvalue: string, exdays: number) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
export function getCookie(cname: string) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment