Active Links & Conditional Rendering
Active Links & Conditional Rendering
1. Implement Active Link Styling
a. Import the usePathname
Hook
usePathname
HookIn your Navbar component, import the
usePathname
hook from Next.js’ navigation module. This hook lets you determine the current route: components/Navbar.jsx
b. Retrieve the Current Pathname
Inside your Navbar component function just below Navbar function, initialize a constant to hold the current pathname:
c. Apply Conditional Styling to Each Link
For each navigation link, adjust the
className
dynamically using a template literal and a ternary operator.Example for the Home Link(/):
Example for the Properties Link(/properties):
Example for the Properties Add Link(/properties/add):
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:
b. Conditionally Render Navbar Items
For Desktop Navigation:
Show “Add Property” Link Only When Logged In:
Toggle Between “Login or Register” (when logged out) and Profile Dropdown (when logged in):
For Mobile Navigation:
Apply the same conditional logic to show/hide links in the mobile menu.
Example:
3. Testing and Final Adjustments
a. Run Your Development Server
Start your Next.js application:
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
isLoggedIn
StateChange the value of
isLoggedIn
(e.g., set it totrue
orfalse
) 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