I am using React and Tailwind. I am trying to conditionally render navbar
elements based on whether a user is logged in or not. The items show in the navbar but they do not change based on whether the user is logged in or not.
export default function Navigation() {
const user = auth.currentUser;
const [isLoggedIn, setIsLoggedIn] = useState("");
//Trying something
let links = [
{ name: "Signup", link: "#", show: !isLoggedIn },
{ name: "Signin", link: "#", show: !isLoggedIn },
{ name: "Logout", link: "#", show: isLoggedIn },
{ name: "Profiles", link: "#" },
{ name: "Contact", link: "#" },
useEffect(() => {
const unsubscribe = onAuthStateChanged(
auth,
(user) => {
console.log(user);
if (user) {
setIsLoggedIn(true);
} else {
setIsLoggedIn(false);
}
},
[]
);
return unsubscribe;
}, []);
return (<ul>
{links.map((link) => {
return (
<li key={link.name}>
<a
href={link.link}
className={`p-2 ${
link.show && (link.show ? "" : "hidden")
}`}
aria-current="page"
>
{link.name}
</a>
</li>
);
})}
</ul>)
2
Answers
Because you have added
link.show && ...
, the second part will only be executed iflink.show
istrue
. So, thehidden
class is never applied to the links. You can fix it by changing the following:Checkout Short-circuit evaluation
2 things to keep in mind:
Initial state of
isLoggedIn
is""
, It should betrue
orfalse
insteadTry adding
auth
object in the dependency array ofuseEffect
hook, to listen to changes in the user’s authentication status.Final, updated code: