Home > Enterprise >  How to Hide and show HTML based on a cookie existing or not in a React App
How to Hide and show HTML based on a cookie existing or not in a React App

Time:05-08

I have a React App that has a login system. When you log in, a cookie is created called "Name". The issue is that when you are logged in, the "Login" button is still showing, and when you are logged out, the "Logout" button is still showing. In other words, the Login and Logout button are always showing, no matter what state you are in. I created this code shown below.

When the website loads, there is a function named "check" that checks if a cookie called Name exists. If it does, "stuff" gets defined to show the Logout button only. otherwise, if there is not a cookie named Name, then "stuff" gets defined to show the Login button only.

When I load the website, nothing shows up. How is it possible (if it is) to show different HTML based on a cookie?

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { useCookies } from "react-cookie";

export default function Grimm() {
  const [cookies, setCookie] = useCookies(["user"]);

    useEffect(() => {
      check()
    }, [])

  
  let stuff;
  function check() {
    if (cookies.Name) {
      let stuff = <Logout/>;
    } else if (!cookies.Name) {
      let stuff = <login/>
  }
  
function Login() {
  return (
    <button>
      Login
    </button>
    );
}

function Logout() {
  return (
    <button>
      Logout
    </button>
  );
}

    return (
      <div>
        {stuff}
      </div>
    );
  }
}

P.S. this is also a test site, The buttons dont do anything, its something for me to work off of. Thanks!

CodePudding user response:

you need to use the correct hook right now you are doing it wrong, you are not storing the value of your cookie inside the components state. you need to do something like this:

  const [cookies, setCookie] = useState(useCookies(["user"]));

you need to somehow store the value of your cookie inside the state of your component

  • Related