Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda