In your Navbar component, import the usePathname hook from Next.js’ navigation module. This hook lets you determine the current route: components/Navbar.jsx
import { usePathname } from 'next/navigation';
b. Retrieve the Current Pathname
Inside your Navbar component function just below Navbar function, initialize a constant to hold the current pathname:
const pathname = usePathname();
c. Apply Conditional Styling to Each Link
For each navigation link, adjust the className dynamically using a template literal and a ternary operator.
Repeat the process for all navigation links (including mobile menu links) so that the active page is highlighted (e.g., with a black background).
2. Implement Conditional Rendering Based on Authentication State
a. Set Up Authentication State
Since the login system isn’t fully implemented yet, use a piece of state (e.g., isLoggedIn) to simulate a user being logged in or not.
Import the useState hook and initialize the state:
"use client";
import { useState } from 'react';
// Inside your component function:
const [isLoggedIn, setIsLoggedIn] = useState(false); // Change to true to simulate a logged-in user
Apply the same conditional logic to show/hide links in the mobile menu.
Example:
{/* Apply the same conditional logic to show/hide links in the mobile menu. */}
{isLoggedIn ? (
<Link
href="/property/add">
className={`${pathname === '/property/add' ? 'bg-black' : ''} block rounded-md px-3 py-2 text-base font-medium`}
>
Add Property
</Link>
)}
{!isLoggedIn && (
<button className="flex items-center text-white bg-gray-700 hover:bg-gray-900 hover:text-white rounded-md px-3 py-2 my-4">
<FaGoogle className="text-white mr-2" />
<span>Login or Register</span>
</button>
)}
3. Testing and Final Adjustments
a. Run Your Development Server
Start your Next.js application:
npm run dev
Navigate to http://localhost:3000 and verify that:
The active link styling correctly highlights the current page.
The Navbar conditionally displays the appropriate links based on the simulated isLoggedIn state.
Result
b. Toggle the isLoggedIn State
Change the value of isLoggedIn (e.g., set it to true or false) and observe the changes in the Navbar for both desktop and mobile views.
c. Debug and Refine CSS Classes
Adjust Tailwind CSS classes as needed to achieve the desired aesthetics and responsiveness.
Recap
Active Link Styling:
Use the usePathname hook to dynamically apply CSS classes based on the current route, ensuring that the active page is visually highlighted.
Conditional Rendering:
Use React state (isLoggedIn) to conditionally render components like the "Add Property" link, login button, and profile dropdown. This approach sets the foundation for future authentication integration.