I'm developing a React app and I need to conditionally render a "Login" or "Logout" button based on the user's current authentication status. However, I'm running into an issue where the conditional statement isn't working as expected. Even after the user is logged in, only the login button is shown and I cannot log out unless both buttons are shown, which is not the desired behavior.
<div className="auth"> { isAuthenticated ? (<button onClick={() => loginWithRedirect()}><CiLogin /></button>) : (<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}><CiLogout /></button>) } </div>
import React from 'react' import { FaTruckMoving } from 'react-icons/fa'; import { AiOutlineHeart, AiOutlineUser } from 'react-icons/ai' import { BsBagCheck } from 'react-icons/bs' import { CiLogin, CiLogout } from 'react-icons/ci' import './Nav.css' import { Link } from 'react-router-dom'; import { useAuth0 } from "@auth0/auth0-react"; const Nav = () => { const { loginWithRedirect, logout, user, isAuthenticated } = useAuth0(); let authButton; if (isAuthenticated) { authButton = ( <button onClick={() => loginWithRedirect()}><CiLogin /></button> ); } else { authButton = ( <button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}><CiLogout /></button> ); } return ( <> <div className="free"> <div className='icon'> <FaTruckMoving /> </div> <p> Free Shipping for Orders upto Rs.1000 </p> </div> <div className="main_header"> <div className="container"> <div className="logo"> <img src="./img/logo.svg" alt="Logo" style={{width:'120px'}}/> </div> <div className="search_box"> <input type="text" defaultValue="" placeholder="Enter the Product Name" autoComplete='off' /> <button>Search</button> </div> <div className="icon"> { isAuthenticated && ( <div className="account"> <div className="user_icon"> <AiOutlineUser /> </div> <p>Hello, {user.name}</p> </div> ) } <div className="second_icon"> <Link to="/" className='link'><AiOutlineHeart /></Link> <Link to="/cart" className='link'><BsBagCheck /></Link> </div> </div> </div> </div> <div className="header"> <div className="container"> <div className="nav"> <ul> <li> <Link to='/' className='link'>Home</Link> </li> <li> <Link to='/product' className='link'>Product</Link> </li> <li> <Link to='/about' className='link'>About</Link> </li> <li> <Link to='/contact' className='link'>Contact</Link> </li> </ul> </div> <div className="auth"> {authButton} </div> </div> </div> </> ) } export default Nav
I tried the above method but still the same result
P粉2450036072023-09-11 11:30:05
You don't have a good approach using isAuthenticated
, if isAuthenticated
is True you need to show the logout button, else if isAuthenticated
is False you need to show the login button .
Try this:
{ isAuthenticated ? (<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}><CiLogout /></button>) : (<button onClick={() => loginWithRedirect()}><CiLogin /></button>) }