orestbida / cookieconsent

:cookie: Simple cross-browser cookie-consent plugin written in vanilla js
https://playground.cookieconsent.orestbida.com/
MIT License
4.05k stars 416 forks source link

[Bug]: Next.js 14: Modal window showPreferences does not open after language switch #753

Open spalz opened 5 days ago

spalz commented 5 days ago

Expected Behavior

The modal window showPreferences should open correctly after switching the language, both via the data attribute and onClick event.

Current Behavior

After switching the language, the modal window showPreferences does not open, neither via the data attribute nor the onClick event.

Steps to reproduce

Reproducing the error: https://stackblitz.com/~/github.com/spalz/CookieConsent

Steps to reproduce:

  1. Switch the language on the page.
  2. Try to open the modal window showPreferences using either the data attribute or the onClick event.
  3. Observe that the modal window does not open.å

Proposed fix or additional info.

Stack:

nextjs: "14.x.x" translate package intl or i18n

https://github.com/user-attachments/assets/83bfee96-30fc-4afd-b120-c2f9180df250

Version

3.0.1

On which browser do you see the issue?

No response

orestbida commented 5 days ago

The language change causes a full page re-render, and the markup generated by the plugin is being destroyed.

Since this is a vanilla js plugin (and not a react component) you need to be extra careful on how you initialize the plugin.

You need to initialize the plugin on a higher level, so that it does not get re-rendered. Here is a demo. Try navigating between pages, and you'll see that the markup is not destroyed.

spalz commented 5 days ago

@orestbida thanks for the reply! I spent the whole day figuring out how to set it up so that it wouldn’t reset when switching languages.

I actually figured out a solution using provider, and I’ll share it later as an example for Next.js with the app router.