I am creating a cookie consent in a react app where users can accept or reject. If the user has already accepted the cookie concept, dont show again.
I want to check on page load if the item is already set, don't display consent else display(html to hidden). But the issue is that onLoad event, the document is not ready. How can I fix this?
Also, I discovered that on page load is hitting the "OnpageLoad()"
Accept and Reject working fine
cookieconsent.ts
const storageType = localStorage;
const consentPropertyName = "jdc_consent";
const saveToStorage = () => storageType.setItem(consentPropertyName, "true");
class UserConsent {
OnpageLoad() {
debugger;
const shouldShowPopUp = storageType.getItem(consentPropertyName);
if (shouldShowPopUp != "true") {
let html = document.getElementById("consent-pop") as HTMLElement;
html.classList.add("hidden");
}
}
async acceptConsent() {
debugger;
saveToStorage();
let html = document.getElementById("consent-pop") as HTMLElement;
html.classList.add("hidden");
//html.style.display === "block";
}
async rejectConcent() {
storageType.removeItem(consentPropertyName);
let html = document.getElementById("consent-pop") as HTMLElement;
html.classList.add("hidden");
}
}
export default new UserConsent();
view.tsx
<div>
<div>
...
</div>
<div
id="consent-pop"
onLoad={cookieconsent.OnpageLoad}
style={{
position: "fixed",
bottom: 0,
left: 0,
right: "0",
}}
className="visible"
>
<p>
By using this site you agree to our Terms and Conditions{" "}
<a onClick={cookieconsent.acceptConsent}>Accept</a> or{" "}
<a onClick={cookieconsent.rejectConcent}>Reject</a>
</p>
</div>
</div>
Try this:
const storageType = localStorage;
const consentPropertyName = "jdc_consent";
const saveToStorage = () => storageType.setItem(consentPropertyName, "true");
class UserConsent {
componentDidMount() {
window.addEventListener('load', this.handleLoad);
}
handleLoad() {
debugger;
const shouldShowPopUp = storageType.getItem(consentPropertyName);
if (shouldShowPopUp != "true") {
let html = document.getElementById("consent-pop") as HTMLElement;
html.classList.add("hidden");
}
}
async acceptConsent() {
debugger;
saveToStorage();
let html = document.getElementById("consent-pop") as HTMLElement;
html.classList.add("hidden");
//html.style.display === "block";
}
async rejectConcent() {
storageType.removeItem(consentPropertyName);
let html = document.getElementById("consent-pop") as HTMLElement;
html.classList.add("hidden");
}
}
export default new UserConsent();
Maybe like alternative try with useEffect also.