reactjsnext.jslocal-storageparentchildren

put information in localStorage with react


I am working on a showcase website for an alcohol brand and I would like when the site is initialized, a component (a modal that i already create) is displayed for the user's first visit, but not for the following.

My component (legalAge) is a modal that the purpose is to ask if the user is major ^^

my component

where i would like to put it conditionnaly

I would therefore like to create a variable in the form of a bolean in local storage but I don't really know how to go about it.

i mean i know create the information in the local Storage but i don't know how to use it...

I know that this practice is not very reliable in terms of security but I will put up with it for the moment


Solution

  • In your LegalAge Modal, set your localStorage in the onClose function as follows:

    const onClose = () => localStorage.setItem("legal_age", JSON.stringify(true));
    

    In your Home component, proceed to get legal_age from localStorage:

    const isLegal = JSON.parse(localStorage.getItem("legal_age"));
    

    Then proceed to use the isLegal variable conditionally by using ternary operators or if-else statements