Joe Kitchen
Joe Kitchen

Reputation: 43

How to show a pop-up for first time users

As a first time user of cookies, I am trying to create a modal that only displays for first-time users to my website.

I am using react and have downloaded the universal-cookie package. So far I am able to check if the cookie exists and if so hides the modal. The second part of the function if the cookie does not exist then should create a cookie and display the modal. At present, the cookie is created but no modal is displayed.

import React, { useState } from 'react';
import styles from './index.module.css';
import Cookies from 'universal-cookie';



function Slide1() {
  const [isOpen, setIsOpen] = useState(true); //Displays Modal
  const cookies = new Cookies('registered');

  const handleCookie = () => {
    if (cookies.get('registered')) {
      return setIsOpen(false); //Modal does not open if cookie exists
    } else if (!cookies.get('registered')) {
      cookies.set('registered', 'true', {
        path: '/',
      });
      return setIsOpen(true); //Creates a cookie and shows modal.
    }
  };

Upvotes: 2

Views: 2336

Answers (2)

fahimchowdhury
fahimchowdhury

Reputation: 474

Try this, Replace

const [isOpen, setIsOpen] = useState(false);

import useEffect,

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

Instead of using handlCookie(), use

useEffect(()=>{
  if (cookies.get('registered')) {
    setIsOpen(false); //Modal does not open if cookie exists
  } else if (!cookies.get('registered')) {
     cookies.set('registered', 'true', {
      path: '/',
     });
     setIsOpen(true); //Creates a cookie and shows modal.
  }
},[])

Remove this from div

onLoad={handleCookie}

Upvotes: 4

VersifiXion
VersifiXion

Reputation: 2292

1/ You can remove the return from these lines I think :

return setIsOpen(false); & return setIsOpen(true);

2/ And in your JSX, you can put {isOpen && ( instead of {isOpen ? (

3/ Then you can remove the : null in the JSX

Upvotes: 0

Related Questions