How to Create a Cookie Consent Form in React: A Step-by-Step Guide

Creating a cookie consent form in React is a crucial step towards making your website GDPR compliant. In this tutorial, we will walk you through the process of creating a cookie consent form using React and JavaScript.

Step 1: Set up your project

First, create a new React project using the command npx create-react-app. Once your project is set up, install the react-cookie package using the command npm install react-cookie.

Step 2: Create a cookie consent component

Next, create a new component for your cookie consent form. This component will contain a checkbox to allow users to consent to cookies and a button to save their preferences. Here is an example code snippet for the component:

tsx
import React, { useState } from 'react';
import { useCookies } from 'react-cookie';

const CookieConsent = () => {
  const [cookies, setCookie] = useCookies(["cookieConsent"]);
  const giveCookieConsent = () => {
    setCookie("cookieConsent", true, { path: "/" });
  };

  return (
    <div className="cookie-consent">
      <p>
        We use cookies to enhance your user experience. By using our website,
        you agree to our use of cookies.{" "}
        <a href={"/privacy-policy"}>Learn more.</a>
      </p>
      <button onClick={giveCookieConsent}>
        Accept
      </button>
    </div>
  );
};

export default CookieConsent;

Step 3: Add the cookie consent component to your website

Now that you have created your cookie consent component, you can add it to your website by importing it into your main app component and rendering it. Here is an example code snippet for the app component:

tsx
import React from 'react';
const App = () => {
 
  return (
    <div className="app">
      <h1>Welcome to my website</h1>
      <CookieConsent />
    </div>
  );
};

export default App;

Step 4: Check if the user has given consent

Finally, you need to check if the user has given consent before setting any cookies. You can do this by checking the value of the cookieConsent cookie using the useCookies hook. Here is an example code snippet:

typescript
import React from 'react';
import CookieConsent from './CookieConsent';

const App = () => {
  const [cookies] = useCookies(["cookieConsent"]);
  
  return (
    <div className="app">
      <h1>Welcome to my website</h1>
      {!cookies.cookieConsent && <CookieConsent />}
    </div>
  );
};

export default App;

That's it! You have successfully created a cookie consent form in React using the react-cookie package. By following these steps, you can make your website GDPR-compliant and ensure that your users' privacy is protected.