DEV Community

Rahul kumar
Rahul kumar

Posted on

Create Cookie banner in React

In this article, we'll see that how can we create cookie banner in react.

The Architecture

This is going to be sort and sweet and assuming that you already know that what is cookie banner, react, etc

The Architecture

The Architecture is simple, we are going to have a CookieBanner component which will have it's own state. It'll show a banner on the UI and when user clicks on the accept or close buttton, the banner will gets removed.

Implementing this in Reach + Chakra-UI

import { useState, useEffect } from "react";
import { BellIcon } from "@chakra-ui/icons";
import {
  Box,
  HStack,
  Icon,
  Stack,
  Text,
  useColorModeValue,
  Button,
} from "@chakra-ui/react";
import { getLocalStorage, setLocalStorage } from "@src/util";

export default function Banner() {
  // by default do not show this banner
  const [isCookieEnabled, setIsCookieEnabled] = useState(true);

  useEffect(() => {
    const isCookie = getLocalStorage("cookie-enabled");
    setIsCookieEnabled(Boolean(isCookie));
  }, []);

  return isCookieEnabled ? null : (
    <Box as="section" pt="8" pb="12" pos="fixed" bottom={"-50px"} w="100%" zIndex={10}>
      <Stack
        direction={{ base: "column", sm: "row" }}
        justifyContent="center"
        alignItems="center"
        py="3"
        px={{ base: "3", md: "6", lg: "8" }}
        color="white"
        bg={useColorModeValue("blue.600", "blue.400")}
      >
        <HStack spacing="3">
          <Icon as={BellIcon} fontSize="2xl" h="10" />
          <Text fontWeight="medium" marginEnd="2">
            By using our website, you agree to the use of cookies as described
            in our cookie policy
          </Text>
        </HStack>
        <Button
          w={{ base: "full", sm: "auto" }}
          flexShrink={0}
          colorScheme="green"
          onClick={() => {
            setLocalStorage("cookie-enabled", true);
            setIsCookieEnabled(true);
          }}
        >
          Accept
        </Button>
      </Stack>
    </Box>
  );
}
Enter fullscreen mode Exit fullscreen mode

Desktop

Image description

Mobile

Image description
To see this in action open this page.

Thank You

Top comments (0)