Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!