Grimm
Grimm

Reputation: 43

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

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!

Upvotes: 1

Views: 1276

Answers (2)

Morten Hansen
Morten Hansen

Reputation: 1

How about using Conditional Operator?

return (
    <div>
    {
    cookies.Name ? <Logout /> : <Login />
    }
    </div>
    )

The conditional operator check if a condition is true, and then run either a true or a false expression based on the condition.

By typing cookies.Name ? as the condition we check if the there is a cookie.Name and if found it returns true. The expression after the ? is to render out the <Logout /> component if the condition is true.

If there isn't a cookie.Name then the condition is false. If the condition is false then the part after : is what runs. Therefor we want it to render the <Login /> component if there is no cookie.Name.

Upvotes: 0

Mamdasan
Mamdasan

Reputation: 323

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

Upvotes: 2

Related Questions