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 have already created) 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 conditionally

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

I mean I know create the information in 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