niclaszll
niclaszll

Reputation: 390

How do I toggle classes in GatsbyJS depended on a cookie?

I want to do a simple cookie notice for my Gatsby Hobby Page without the use of extra cookie npm packages.

I successfully set the cookie with the use of the 'universal-cookie' npm package. I change the state when I click the 'close' button of the consent banner and it does hide the banner. But when I'm now reloading my page the banner still shows up, even though cookie and state are correctly set (checked via console.log).

import React from 'react'
import Cookie from 'universal-cookie'

const cookie = new Cookie()

class CookieNotice extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      active: cookie.get('viewed_cookie_notice'),
    }
    this.toggleActiveClass = this.toggleActiveClass.bind(this)
  }

  componentDidMount() {
    this.setState({ active: cookie.get('viewed_cookie_notice') })
  }

  toggleActiveClass() {
    cookie.set('viewed_cookie_notice', true, { path: '/', expires: new Date(Date.now() + 2592000) })
    this.setState({ active: cookie.get('viewed_cookie_notice') })
  }

  render() {
    const { active } = this.state
    return (
      <div id="cookie-notice" className={active ? 'hidden' : null}>
          <button type="button" id="close-cookie" onClick={this.toggleActiveClass}>
            Close!
          </button>
        </div>
      </div>
    )
  }
}
export default CookieNotice

I just want to hide the cookie banner permanently, if the user has closed the cookie banner and not show it to him every time he revisits the page.

Upvotes: 1

Views: 491

Answers (1)

Ladi Adenusi
Ladi Adenusi

Reputation: 1082

In your constructor, change the value of active in the state.

constructor(props) {
  super(props);
  this.state = { active: true };
}

By setting the value of active to true, it means that when the component first loads, the banner will be hidden, and then by calling setState in componentDidMount, it will get the value of the cookie and then re-render with the right value.

Upvotes: 2

Related Questions