0
votes

I'm using the 'react-cookie' package:

https://www.npmjs.com/package/react-cookie

From this documentation, I've built the following JSX components which successfully creates a cookie called 'cookieConsent' and stores its value as 'true' if the accept button is pressed.

const CookiePopup = () => {

  const [cookies, setCookie] = useCookies(false);

  const onClick = () => {
    setCookie('cookieConsent', true)
  }

  return (

    <div className="cookie-popup-container">
      <div className="cookie-consent-text">
        <p className="cookie-consent-paragraph">By using our website, you agree to our <a className="cookie-consent-link" href="/cookies" target="_blank">cookie policy</a>.</p>
      </div>
      <div className="cookie-consent-button">
        <button className="cookie-button" onClick={onClick}>Yep, sure thing!</button>
      </div>
    </div>

  )
}

What I then want to do is conditionally render this component. If the cookieConsent cookie exists and the value is 'true' (which it always will be), I want this component to be null. If it doesn't exist, I want to render the component.

I'm trying to do this conditional render like so:

{ cookies.value !== true ?  <div className="cookie-popup-container">
      <div className="cookie-consent-text">
        <p className="cookie-consent-paragraph">By using our website, you agree to our <a className="cookie-consent-link" href="/cookies" target="_blank">cookie policy</a>.</p>
      </div>
      <div className="cookie-consent-button">
        <button className="cookie-button" onClick={onClick}>Yep, sure thing!</button>
      </div>
    </div> : null }

However, it's coming up with a 'unexpected token, expected "," within the 'value' bit of 'cookies.value'.

I think this might be because this is a child component, and I'm attempting to render it in a parent component - so maybe I need to render it differently in my parent component rather than just importing.

For reference, this is how I'm doing it in my 'homepage' component:

import CookiePopup from '../elements/cookie-popup'

const Homepage = () => {

  return (
    <>
      <CookiePopup />
    </>
  )
}

Any advice or pointers would be really appreciated! My first time using cookies so I'm sure I'm missing something obvious.

1
What does console.log(cookies) print? - Nemanja Lazarevic

1 Answers

0
votes

You can leave useCookies() empty or specify the names of the cookies that you expect to use.

const [cookies, setCookie] = useCookies();

Conditionally render

{ cookies.cookieConsent && (
  <div>{"your HTML Here"}</div>
)}