Active Links & Conditional Rendering

a. Import the usePathname Hook

  • 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();
  • For each navigation link, adjust the className dynamically using a template literal and a ternary operator.

  • Example for the Home Link(/):

    <Link 
        href="/"
        className={`${pathname === '/' ? 'bg-black' : ''} px-3 py-2 text-white hover:bg-gray-900 rounded-md`}
        
        >
        Home
    </Link>
  • Example for the Properties Link(/properties):

    <Link 
       href="/properties">
       className={`${pathname === '/properties' ? 'bg-black' : ''} px-3 py-2 text-white hover:bg-gray-900 rounded-md`}
       >
       Properties
    </Link>
  • Example for the Properties Add Link(/properties/add):

    <Link 
       href="/properties/add">
       className={`${pathname === '/properties/add' ? 'bg-black' : ''} px-3 py-2 text-white hover:bg-gray-900 rounded-md`}
       >
       Add Properties
    </Link>
  • 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

b. Conditionally Render Navbar Items

  • For Desktop Navigation:

    • Show “Add Property” Link Only When Logged In:

      {isLoggedIn && (
        <Link 
          href="/property/add">
          className={`${pathname === '/property/add' ? 'bg-black' : ''} px-3 py-2 text-white hover:bg-gray-900 rounded-md`}
          >
          Add Property   
        </Link>
      )}
    • Toggle Between “Login or Register” (when logged out) and Profile Dropdown (when logged in):

      {/* <!-- Right Side Menu (Logged Out) --> */}
      {!isLoggedIn ? (
        <div className="flex items-center">
          <button className="flex items-center text-white bg-gray-700 hover:bg-gray-900 rounded-md px-3 py-2">
            Login or Register
          </button>
        </div>
      ) } 
      
      {/* <!-- Right Side Menu (Logged In) --> */}
      
         {isLoggedIn && (
                  <div className="absolute inset-y-0 right-0 flex items-center pr-2 md:static md:inset-auto md:ml-6 md:pr-0">
                    <Link href="/messages" className="relative group">
                      <button
                        type="button"
                        className="relative rounded-full bg-gray-800 p-1 text-gray-400 hover:text-white focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-gray-800">
                        <span className="absolute -inset-1.5"></span>
                        <span className="sr-only">View notifications</span>
                        <svg
                          className="h-6 w-6"
                          fill="none"
                          viewBox="0 0 24 24"
                          strokeWidth="1.5"
                          stroke="currentColor"
                          aria-hidden="true">
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0"
                          />
                        </svg>
                      </button>
                      <span className="absolute top-0 right-0 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white transform translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full">
                        {' '}
                        2
                        {/* <!-- Replace with the actual number of notifications --> */}
                      </span>
                    </Link>
                    {/* <!-- Profile dropdown button --> */}
                    <div className="relative ml-3">
                      <div>
                        <button
                          type="button"
                          className="relative flex rounded-full bg-gray-800 text-sm focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-gray-800"
                          id="user-menu-button"
                          aria-expanded={isProfileMenuOpen}
                          aria-haspopup="true"
                          onClick={() => setIsProfileMenuOpen((prev) => !prev)}>
                          <span className="absolute -inset-1.5"></span>
                          <span className="sr-only">Open user menu</span>
                          <Image
                            className="h-8 w-8 rounded-full"
                            src={profileDefault}
                            alt=""
                          />
                        </button>
                      </div>
      
                      {/* <!-- Profile hide/show dropdown --> */}
                      {isProfileMenuOpen && (
                        <div
                          id="user-menu"
                          className=" absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
                          role="menu"
                          aria-orientation="vertical"
                          aria-labelledby="user-menu-button"
                          tabIndex="-1">
                          <Link
                            href="/profile"
                            className="block px-4 py-2 text-sm text-gray-700"
                            role="menuitem"
                            tabIndex="-1"
                            id="user-menu-item-0">
                            Your Profile
                          </Link>
                          <Link
                            href="/profiles/saved"
                            className="block px-4 py-2 text-sm text-gray-700"
                            role="menuitem"
                            tabIndex="-1"
                            id="user-menu-item-2">
                            Saved Properties
                          </Link>
                          <Link
                            href="#"
                            className="block px-4 py-2 text-sm text-gray-700"
                            role="menuitem"
                            tabIndex="-1"
                            id="user-menu-item-2">
                            Sign Out
                          </Link>
                        </div>
                      )}
                    </div>
                  </div>
                )}
  • For Mobile Navigation:

    • 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.

Last updated